repo_name
stringlengths 8
38
| pr_number
int64 3
47.1k
| pr_title
stringlengths 8
175
| pr_description
stringlengths 2
19.8k
⌀ | author
null | date_created
stringlengths 25
25
| date_merged
stringlengths 25
25
| filepath
stringlengths 6
136
| before_content
stringlengths 54
884k
⌀ | after_content
stringlengths 56
884k
| pr_author
stringlengths 3
21
| previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| comment
stringlengths 2
25.4k
| comment_author
stringlengths 3
29
| __index_level_0__
int64 0
5.1k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
posativ/isso | 845 | [client] Highlight linked comments to identify them | Fixes #838
TODO:
- [x] Figure out the best way to do styling
- [x] Docs
- [x] Tests (check that `.isso-target` gets applied properly) | null | 2022-04-24 00:32:28+00:00 | 2022-05-20 19:31:57+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
margin: 0 auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
width: 100%;
height: 100%;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
margin: 0 auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
width: 100%;
height: 100%;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
/* "target" means the comment that's being linked to, for example:
* https://example.com/blog/example/#isso-15
*/
.isso-target {
animation: isso-target-fade 5s ease-out;
}
@keyframes isso-target-fade {
0% { background-color: #eee5a1; }
/* This color should be changed when used on a dark background,
* maybe #3f3c1c for example
*/
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 8d2f799ae3737ef6385bf0a740c8fee03d90601e | 1015aaa073607b4210a8ad8b35ebd83806578dfd | That animation name should be isso-namespaced | ix5 | 25 |
posativ/isso | 845 | [client] Highlight linked comments to identify them | Fixes #838
TODO:
- [x] Figure out the best way to do styling
- [x] Docs
- [x] Tests (check that `.isso-target` gets applied properly) | null | 2022-04-24 00:32:28+00:00 | 2022-05-20 19:31:57+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
margin: 0 auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
width: 100%;
height: 100%;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
margin: 0 auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
width: 100%;
height: 100%;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
/* "target" means the comment that's being linked to, for example:
* https://example.com/blog/example/#isso-15
*/
.isso-target {
animation: isso-target-fade 5s ease-out;
}
@keyframes isso-target-fade {
0% { background-color: #eee5a1; }
/* This color should be changed when used on a dark background,
* maybe #3f3c1c for example
*/
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 8d2f799ae3737ef6385bf0a740c8fee03d90601e | 1015aaa073607b4210a8ad8b35ebd83806578dfd | This color (light yellow) is quite jarring on dark background. Try e.g. the demo with `body { background: black; color: white; }`
Also, maybe add a little code comment such as `Flash comment light yellow when focussed`, either here or in embed.js | ix5 | 26 |
posativ/isso | 845 | [client] Highlight linked comments to identify them | Fixes #838
TODO:
- [x] Figure out the best way to do styling
- [x] Docs
- [x] Tests (check that `.isso-target` gets applied properly) | null | 2022-04-24 00:32:28+00:00 | 2022-05-20 19:31:57+00:00 | isso/js/embed.js | /*
* Copyright 2014, Martin Zimmermann <info@posativ.org>. All rights reserved.
* Distributed under the MIT license
*/
var domready = require("app/lib/ready");
var config = require("app/config");
var i18n = require("app/i18n");
var api = require("app/api");
var isso = require("app/isso");
var count = require("app/count");
var $ = require("app/dom");
var svg = require("app/svg");
var template = require("app/template");
"use strict";
template.set("conf", config);
template.set("i18n", i18n.translate);
template.set("pluralize", i18n.pluralize);
template.set("svg", svg);
var isso_thread;
var heading;
function init() {
isso_thread = $('#isso-thread');
heading = $.new("h4");
if (config["css"] && $("style#isso-style") === null) {
var style = $.new("link");
style.id = "isso-style";
style.rel ="stylesheet";
style.type = "text/css";
style.href = config["css-url"] ? config["css-url"] : api.endpoint + "/css/isso.css";
$("head").append(style);
}
count();
if (isso_thread === null) {
return console.log("abort, #isso-thread is missing");
}
if (config["feed"]) {
var feedLink = $.new('a', i18n.translate('atom-feed'));
var feedLinkWrapper = $.new('span.isso-feedlink');
feedLink.href = api.feed(isso_thread.getAttribute("data-isso-id"));
feedLinkWrapper.appendChild(feedLink);
isso_thread.append(feedLinkWrapper);
}
// Note: Not appending the isso.Postbox here since it relies
// on the config object populated by elements fetched from the server,
// and the call to fetch those is in fetchComments()
isso_thread.append(heading);
isso_thread.append('<div id="isso-root"></div>');
}
function fetchComments() {
if (!$('#isso-root')) {
return;
}
var isso_root = $('#isso-root');
isso_root.textContent = '';
api.fetch(isso_thread.getAttribute("data-isso-id") || location.pathname,
config["max-comments-top"],
config["max-comments-nested"]).then(
function (rv) {
for (var setting in rv.config) {
if (setting in config && config[setting] != rv.config[setting]) {
console.log("Isso: Client value '%s' for setting '%s' overridden by server value '%s'.\n" +
"Since Isso version 0.12.6, 'data-isso-%s' is only configured via the server " +
"to keep client and server in sync",
config[setting], setting, rv.config[setting], setting);
}
config[setting] = rv.config[setting]
}
// Note: isso.Postbox relies on the config object populated by elements
// fetched from the server, so it cannot be created in init()
isso_root.prepend(new isso.Postbox(null));
if (rv.total_replies === 0) {
heading.textContent = i18n.translate("no-comments");
return;
}
var lastcreated = 0;
var count = rv.total_replies;
rv.replies.forEach(function(comment) {
isso.insert(comment, false);
if (comment.created > lastcreated) {
lastcreated = comment.created;
}
count = count + comment.total_replies;
});
heading.textContent = i18n.pluralize("num-comments", count);
if (rv.hidden_replies > 0) {
isso.insert_loader(rv, lastcreated);
}
if (window.location.hash.length > 0 &&
window.location.hash.match("^#isso-[0-9]+$")) {
$(window.location.hash).scrollIntoView();
}
},
function(err) {
console.log(err);
}
);
}
domready(function() {
init();
fetchComments();
});
window.Isso = {
init: init,
fetchComments: fetchComments
};
| /*
* Copyright 2014, Martin Zimmermann <info@posativ.org>. All rights reserved.
* Distributed under the MIT license
*/
var domready = require("app/lib/ready");
var config = require("app/config");
var i18n = require("app/i18n");
var api = require("app/api");
var isso = require("app/isso");
var count = require("app/count");
var $ = require("app/dom");
var svg = require("app/svg");
var template = require("app/template");
"use strict";
template.set("conf", config);
template.set("i18n", i18n.translate);
template.set("pluralize", i18n.pluralize);
template.set("svg", svg);
var isso_thread;
var heading;
function init() {
isso_thread = $('#isso-thread');
heading = $.new("h4");
if (config["css"] && $("style#isso-style") === null) {
var style = $.new("link");
style.id = "isso-style";
style.rel ="stylesheet";
style.type = "text/css";
style.href = config["css-url"] ? config["css-url"] : api.endpoint + "/css/isso.css";
$("head").append(style);
}
count();
if (isso_thread === null) {
return console.log("abort, #isso-thread is missing");
}
if (config["feed"]) {
var feedLink = $.new('a', i18n.translate('atom-feed'));
var feedLinkWrapper = $.new('span.isso-feedlink');
feedLink.href = api.feed(isso_thread.getAttribute("data-isso-id"));
feedLinkWrapper.appendChild(feedLink);
isso_thread.append(feedLinkWrapper);
}
// Note: Not appending the isso.Postbox here since it relies
// on the config object populated by elements fetched from the server,
// and the call to fetch those is in fetchComments()
isso_thread.append(heading);
isso_thread.append('<div id="isso-root"></div>');
window.addEventListener('hashchange', function() {
if (!window.location.hash.match("^#isso-[0-9]+$")) {
return;
}
var existingTarget = $(".isso-target");
if (existingTarget != null) {
existingTarget.classList.remove("isso-target");
}
$(window.location.hash + " > .isso-text-wrapper").classList.add("isso-target");
});
}
function fetchComments() {
if (!$('#isso-root')) {
return;
}
var isso_root = $('#isso-root');
isso_root.textContent = '';
api.fetch(isso_thread.getAttribute("data-isso-id") || location.pathname,
config["max-comments-top"],
config["max-comments-nested"]).then(
function (rv) {
for (var setting in rv.config) {
if (setting in config && config[setting] != rv.config[setting]) {
console.log("Isso: Client value '%s' for setting '%s' overridden by server value '%s'.\n" +
"Since Isso version 0.12.6, 'data-isso-%s' is only configured via the server " +
"to keep client and server in sync",
config[setting], setting, rv.config[setting], setting);
}
config[setting] = rv.config[setting]
}
// Note: isso.Postbox relies on the config object populated by elements
// fetched from the server, so it cannot be created in init()
isso_root.prepend(new isso.Postbox(null));
if (rv.total_replies === 0) {
heading.textContent = i18n.translate("no-comments");
return;
}
var lastcreated = 0;
var count = rv.total_replies;
rv.replies.forEach(function(comment) {
isso.insert(comment, false);
if (comment.created > lastcreated) {
lastcreated = comment.created;
}
count = count + comment.total_replies;
});
heading.textContent = i18n.pluralize("num-comments", count);
if (rv.hidden_replies > 0) {
isso.insert_loader(rv, lastcreated);
}
if (window.location.hash.length > 0 &&
window.location.hash.match("^#isso-[0-9]+$")) {
$(window.location.hash).scrollIntoView();
// We can't just set the id to `#isso-target` because it's already set to `#isso-[number]`
// So a class `.isso-target` has to be used instead, and then we can manually remove the
// class from the old target comment in the `hashchange` listener.
$(window.location.hash + " > .isso-text-wrapper").classList.add("isso-target");
}
},
function(err) {
console.log(err);
}
);
}
domready(function() {
init();
fetchComments();
});
window.Isso = {
init: init,
fetchComments: fetchComments
};
| BBaoVanC | 8d2f799ae3737ef6385bf0a740c8fee03d90601e | 1015aaa073607b4210a8ad8b35ebd83806578dfd | Wrap this in a try-catch block (ES5 has it, I think?) or check if `$(window.location.hash` actually returns an element. `fetchComments` (and `init`) is a function that definitely should not throw. | ix5 | 27 |
posativ/isso | 845 | [client] Highlight linked comments to identify them | Fixes #838
TODO:
- [x] Figure out the best way to do styling
- [x] Docs
- [x] Tests (check that `.isso-target` gets applied properly) | null | 2022-04-24 00:32:28+00:00 | 2022-05-20 19:31:57+00:00 | isso/js/embed.js | /*
* Copyright 2014, Martin Zimmermann <info@posativ.org>. All rights reserved.
* Distributed under the MIT license
*/
var domready = require("app/lib/ready");
var config = require("app/config");
var i18n = require("app/i18n");
var api = require("app/api");
var isso = require("app/isso");
var count = require("app/count");
var $ = require("app/dom");
var svg = require("app/svg");
var template = require("app/template");
"use strict";
template.set("conf", config);
template.set("i18n", i18n.translate);
template.set("pluralize", i18n.pluralize);
template.set("svg", svg);
var isso_thread;
var heading;
function init() {
isso_thread = $('#isso-thread');
heading = $.new("h4");
if (config["css"] && $("style#isso-style") === null) {
var style = $.new("link");
style.id = "isso-style";
style.rel ="stylesheet";
style.type = "text/css";
style.href = config["css-url"] ? config["css-url"] : api.endpoint + "/css/isso.css";
$("head").append(style);
}
count();
if (isso_thread === null) {
return console.log("abort, #isso-thread is missing");
}
if (config["feed"]) {
var feedLink = $.new('a', i18n.translate('atom-feed'));
var feedLinkWrapper = $.new('span.isso-feedlink');
feedLink.href = api.feed(isso_thread.getAttribute("data-isso-id"));
feedLinkWrapper.appendChild(feedLink);
isso_thread.append(feedLinkWrapper);
}
// Note: Not appending the isso.Postbox here since it relies
// on the config object populated by elements fetched from the server,
// and the call to fetch those is in fetchComments()
isso_thread.append(heading);
isso_thread.append('<div id="isso-root"></div>');
}
function fetchComments() {
if (!$('#isso-root')) {
return;
}
var isso_root = $('#isso-root');
isso_root.textContent = '';
api.fetch(isso_thread.getAttribute("data-isso-id") || location.pathname,
config["max-comments-top"],
config["max-comments-nested"]).then(
function (rv) {
for (var setting in rv.config) {
if (setting in config && config[setting] != rv.config[setting]) {
console.log("Isso: Client value '%s' for setting '%s' overridden by server value '%s'.\n" +
"Since Isso version 0.12.6, 'data-isso-%s' is only configured via the server " +
"to keep client and server in sync",
config[setting], setting, rv.config[setting], setting);
}
config[setting] = rv.config[setting]
}
// Note: isso.Postbox relies on the config object populated by elements
// fetched from the server, so it cannot be created in init()
isso_root.prepend(new isso.Postbox(null));
if (rv.total_replies === 0) {
heading.textContent = i18n.translate("no-comments");
return;
}
var lastcreated = 0;
var count = rv.total_replies;
rv.replies.forEach(function(comment) {
isso.insert(comment, false);
if (comment.created > lastcreated) {
lastcreated = comment.created;
}
count = count + comment.total_replies;
});
heading.textContent = i18n.pluralize("num-comments", count);
if (rv.hidden_replies > 0) {
isso.insert_loader(rv, lastcreated);
}
if (window.location.hash.length > 0 &&
window.location.hash.match("^#isso-[0-9]+$")) {
$(window.location.hash).scrollIntoView();
}
},
function(err) {
console.log(err);
}
);
}
domready(function() {
init();
fetchComments();
});
window.Isso = {
init: init,
fetchComments: fetchComments
};
| /*
* Copyright 2014, Martin Zimmermann <info@posativ.org>. All rights reserved.
* Distributed under the MIT license
*/
var domready = require("app/lib/ready");
var config = require("app/config");
var i18n = require("app/i18n");
var api = require("app/api");
var isso = require("app/isso");
var count = require("app/count");
var $ = require("app/dom");
var svg = require("app/svg");
var template = require("app/template");
"use strict";
template.set("conf", config);
template.set("i18n", i18n.translate);
template.set("pluralize", i18n.pluralize);
template.set("svg", svg);
var isso_thread;
var heading;
function init() {
isso_thread = $('#isso-thread');
heading = $.new("h4");
if (config["css"] && $("style#isso-style") === null) {
var style = $.new("link");
style.id = "isso-style";
style.rel ="stylesheet";
style.type = "text/css";
style.href = config["css-url"] ? config["css-url"] : api.endpoint + "/css/isso.css";
$("head").append(style);
}
count();
if (isso_thread === null) {
return console.log("abort, #isso-thread is missing");
}
if (config["feed"]) {
var feedLink = $.new('a', i18n.translate('atom-feed'));
var feedLinkWrapper = $.new('span.isso-feedlink');
feedLink.href = api.feed(isso_thread.getAttribute("data-isso-id"));
feedLinkWrapper.appendChild(feedLink);
isso_thread.append(feedLinkWrapper);
}
// Note: Not appending the isso.Postbox here since it relies
// on the config object populated by elements fetched from the server,
// and the call to fetch those is in fetchComments()
isso_thread.append(heading);
isso_thread.append('<div id="isso-root"></div>');
window.addEventListener('hashchange', function() {
if (!window.location.hash.match("^#isso-[0-9]+$")) {
return;
}
var existingTarget = $(".isso-target");
if (existingTarget != null) {
existingTarget.classList.remove("isso-target");
}
$(window.location.hash + " > .isso-text-wrapper").classList.add("isso-target");
});
}
function fetchComments() {
if (!$('#isso-root')) {
return;
}
var isso_root = $('#isso-root');
isso_root.textContent = '';
api.fetch(isso_thread.getAttribute("data-isso-id") || location.pathname,
config["max-comments-top"],
config["max-comments-nested"]).then(
function (rv) {
for (var setting in rv.config) {
if (setting in config && config[setting] != rv.config[setting]) {
console.log("Isso: Client value '%s' for setting '%s' overridden by server value '%s'.\n" +
"Since Isso version 0.12.6, 'data-isso-%s' is only configured via the server " +
"to keep client and server in sync",
config[setting], setting, rv.config[setting], setting);
}
config[setting] = rv.config[setting]
}
// Note: isso.Postbox relies on the config object populated by elements
// fetched from the server, so it cannot be created in init()
isso_root.prepend(new isso.Postbox(null));
if (rv.total_replies === 0) {
heading.textContent = i18n.translate("no-comments");
return;
}
var lastcreated = 0;
var count = rv.total_replies;
rv.replies.forEach(function(comment) {
isso.insert(comment, false);
if (comment.created > lastcreated) {
lastcreated = comment.created;
}
count = count + comment.total_replies;
});
heading.textContent = i18n.pluralize("num-comments", count);
if (rv.hidden_replies > 0) {
isso.insert_loader(rv, lastcreated);
}
if (window.location.hash.length > 0 &&
window.location.hash.match("^#isso-[0-9]+$")) {
$(window.location.hash).scrollIntoView();
// We can't just set the id to `#isso-target` because it's already set to `#isso-[number]`
// So a class `.isso-target` has to be used instead, and then we can manually remove the
// class from the old target comment in the `hashchange` listener.
$(window.location.hash + " > .isso-text-wrapper").classList.add("isso-target");
}
},
function(err) {
console.log(err);
}
);
}
domready(function() {
init();
fetchComments();
});
window.Isso = {
init: init,
fetchComments: fetchComments
};
| BBaoVanC | 8d2f799ae3737ef6385bf0a740c8fee03d90601e | 1015aaa073607b4210a8ad8b35ebd83806578dfd | Could you elaborate on what you meant by that code comment? | ix5 | 28 |
posativ/isso | 845 | [client] Highlight linked comments to identify them | Fixes #838
TODO:
- [x] Figure out the best way to do styling
- [x] Docs
- [x] Tests (check that `.isso-target` gets applied properly) | null | 2022-04-24 00:32:28+00:00 | 2022-05-20 19:31:57+00:00 | isso/js/embed.js | /*
* Copyright 2014, Martin Zimmermann <info@posativ.org>. All rights reserved.
* Distributed under the MIT license
*/
var domready = require("app/lib/ready");
var config = require("app/config");
var i18n = require("app/i18n");
var api = require("app/api");
var isso = require("app/isso");
var count = require("app/count");
var $ = require("app/dom");
var svg = require("app/svg");
var template = require("app/template");
"use strict";
template.set("conf", config);
template.set("i18n", i18n.translate);
template.set("pluralize", i18n.pluralize);
template.set("svg", svg);
var isso_thread;
var heading;
function init() {
isso_thread = $('#isso-thread');
heading = $.new("h4");
if (config["css"] && $("style#isso-style") === null) {
var style = $.new("link");
style.id = "isso-style";
style.rel ="stylesheet";
style.type = "text/css";
style.href = config["css-url"] ? config["css-url"] : api.endpoint + "/css/isso.css";
$("head").append(style);
}
count();
if (isso_thread === null) {
return console.log("abort, #isso-thread is missing");
}
if (config["feed"]) {
var feedLink = $.new('a', i18n.translate('atom-feed'));
var feedLinkWrapper = $.new('span.isso-feedlink');
feedLink.href = api.feed(isso_thread.getAttribute("data-isso-id"));
feedLinkWrapper.appendChild(feedLink);
isso_thread.append(feedLinkWrapper);
}
// Note: Not appending the isso.Postbox here since it relies
// on the config object populated by elements fetched from the server,
// and the call to fetch those is in fetchComments()
isso_thread.append(heading);
isso_thread.append('<div id="isso-root"></div>');
}
function fetchComments() {
if (!$('#isso-root')) {
return;
}
var isso_root = $('#isso-root');
isso_root.textContent = '';
api.fetch(isso_thread.getAttribute("data-isso-id") || location.pathname,
config["max-comments-top"],
config["max-comments-nested"]).then(
function (rv) {
for (var setting in rv.config) {
if (setting in config && config[setting] != rv.config[setting]) {
console.log("Isso: Client value '%s' for setting '%s' overridden by server value '%s'.\n" +
"Since Isso version 0.12.6, 'data-isso-%s' is only configured via the server " +
"to keep client and server in sync",
config[setting], setting, rv.config[setting], setting);
}
config[setting] = rv.config[setting]
}
// Note: isso.Postbox relies on the config object populated by elements
// fetched from the server, so it cannot be created in init()
isso_root.prepend(new isso.Postbox(null));
if (rv.total_replies === 0) {
heading.textContent = i18n.translate("no-comments");
return;
}
var lastcreated = 0;
var count = rv.total_replies;
rv.replies.forEach(function(comment) {
isso.insert(comment, false);
if (comment.created > lastcreated) {
lastcreated = comment.created;
}
count = count + comment.total_replies;
});
heading.textContent = i18n.pluralize("num-comments", count);
if (rv.hidden_replies > 0) {
isso.insert_loader(rv, lastcreated);
}
if (window.location.hash.length > 0 &&
window.location.hash.match("^#isso-[0-9]+$")) {
$(window.location.hash).scrollIntoView();
}
},
function(err) {
console.log(err);
}
);
}
domready(function() {
init();
fetchComments();
});
window.Isso = {
init: init,
fetchComments: fetchComments
};
| /*
* Copyright 2014, Martin Zimmermann <info@posativ.org>. All rights reserved.
* Distributed under the MIT license
*/
var domready = require("app/lib/ready");
var config = require("app/config");
var i18n = require("app/i18n");
var api = require("app/api");
var isso = require("app/isso");
var count = require("app/count");
var $ = require("app/dom");
var svg = require("app/svg");
var template = require("app/template");
"use strict";
template.set("conf", config);
template.set("i18n", i18n.translate);
template.set("pluralize", i18n.pluralize);
template.set("svg", svg);
var isso_thread;
var heading;
function init() {
isso_thread = $('#isso-thread');
heading = $.new("h4");
if (config["css"] && $("style#isso-style") === null) {
var style = $.new("link");
style.id = "isso-style";
style.rel ="stylesheet";
style.type = "text/css";
style.href = config["css-url"] ? config["css-url"] : api.endpoint + "/css/isso.css";
$("head").append(style);
}
count();
if (isso_thread === null) {
return console.log("abort, #isso-thread is missing");
}
if (config["feed"]) {
var feedLink = $.new('a', i18n.translate('atom-feed'));
var feedLinkWrapper = $.new('span.isso-feedlink');
feedLink.href = api.feed(isso_thread.getAttribute("data-isso-id"));
feedLinkWrapper.appendChild(feedLink);
isso_thread.append(feedLinkWrapper);
}
// Note: Not appending the isso.Postbox here since it relies
// on the config object populated by elements fetched from the server,
// and the call to fetch those is in fetchComments()
isso_thread.append(heading);
isso_thread.append('<div id="isso-root"></div>');
window.addEventListener('hashchange', function() {
if (!window.location.hash.match("^#isso-[0-9]+$")) {
return;
}
var existingTarget = $(".isso-target");
if (existingTarget != null) {
existingTarget.classList.remove("isso-target");
}
$(window.location.hash + " > .isso-text-wrapper").classList.add("isso-target");
});
}
function fetchComments() {
if (!$('#isso-root')) {
return;
}
var isso_root = $('#isso-root');
isso_root.textContent = '';
api.fetch(isso_thread.getAttribute("data-isso-id") || location.pathname,
config["max-comments-top"],
config["max-comments-nested"]).then(
function (rv) {
for (var setting in rv.config) {
if (setting in config && config[setting] != rv.config[setting]) {
console.log("Isso: Client value '%s' for setting '%s' overridden by server value '%s'.\n" +
"Since Isso version 0.12.6, 'data-isso-%s' is only configured via the server " +
"to keep client and server in sync",
config[setting], setting, rv.config[setting], setting);
}
config[setting] = rv.config[setting]
}
// Note: isso.Postbox relies on the config object populated by elements
// fetched from the server, so it cannot be created in init()
isso_root.prepend(new isso.Postbox(null));
if (rv.total_replies === 0) {
heading.textContent = i18n.translate("no-comments");
return;
}
var lastcreated = 0;
var count = rv.total_replies;
rv.replies.forEach(function(comment) {
isso.insert(comment, false);
if (comment.created > lastcreated) {
lastcreated = comment.created;
}
count = count + comment.total_replies;
});
heading.textContent = i18n.pluralize("num-comments", count);
if (rv.hidden_replies > 0) {
isso.insert_loader(rv, lastcreated);
}
if (window.location.hash.length > 0 &&
window.location.hash.match("^#isso-[0-9]+$")) {
$(window.location.hash).scrollIntoView();
// We can't just set the id to `#isso-target` because it's already set to `#isso-[number]`
// So a class `.isso-target` has to be used instead, and then we can manually remove the
// class from the old target comment in the `hashchange` listener.
$(window.location.hash + " > .isso-text-wrapper").classList.add("isso-target");
}
},
function(err) {
console.log(err);
}
);
}
domready(function() {
init();
fetchComments();
});
window.Isso = {
init: init,
fetchComments: fetchComments
};
| BBaoVanC | 8d2f799ae3737ef6385bf0a740c8fee03d90601e | 1015aaa073607b4210a8ad8b35ebd83806578dfd | Yep, can't believe I didn't catch this error when I was testing. (It happens if you click a comment for the first time, before another one was linked, meaning there is no .isso-target) | BBaoVanC | 29 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | CHANGES.rst | Changelog for Isso
==================
%(version)s (%(date)s)
- **BREAKING:** css, js: Prefix all classes with ``isso-`` (#816, ix5)
Now Isso's CSS is "namespaced" in order not to conflict with other classes on
the page.
This change necessitates adjusting custom CSS files to the new names.
- Drop support for outdated Python version 3.5
(#808, l33tname)
- Fix avatar sizing, limit default gravatar images to 55px (#831, l33tname)
In case of a custom gravatar URL, the ``&s=55`` size parameter will have
to be added, see `Gravatar: Image requests`_.
- Add ``data-isso-reply-notifications-default-enabled`` option to configure
whether or not the subscribe to replies checkbox should be checked by default.
- Accessibility: Use labels rather than placeholders for name, email & website
in post box (`#861 <https://github.com/posativ/isso/pull/861>`_, ix5)
- Re-enable ``no-intra-emphasis`` misaka extension in default config.
- Allow ``sup`` and ``sub`` HTML elements by default
.. _Gravatar: Image requests: http://en.gravatar.com/site/implement/images/
0.12.6 (2022-03-06)
-------------------
- Serve isso.css separately to avoid ``style-src: unsafe-inline`` CSP and allow
clients to override fetch location (#704, ix5):
data-isso-css-url="https://comments.example.org/css/isso.css"
- New "samesite" option in [server] section to override SameSite header for
cookies. (#700, ix5)
- Fallback for SameSite header depending on whether host is served over https
or http (#700, ix5)
- Have client read out shared settings from server. (#311, pellenilsson)
This affects these settings for which ``data-isso-*`` values will be ignored:
[general]
reply-notifications
gravatar
[guard]
reply-to-self
require-author
require-email
- Improved detection of browser-supplied language preferences (#521)
Isso will now honor the newer ``navigator.languages`` global property
as well as ``navigator.language`` and ``navigator.userLanguage``.
There is a new configuration property ``data-isso-default-lang``
that specifies the language to use (instead of English) when none
of these is available. (The existing ``data-isso-lang`` *overrides*
browser-supplied language preferences.)
- Remove ``ISSO_CORS_ORIGIN`` environ variable, which never worked at all
(#803, ix5)
0.12.5 (2021-03-09)
-------------------
- Don't ignore missing configuration files.
(Jelmer Vernooij)
0.12.4 (2021-02-03)
-------------------
- Require Python >= 3.5, for consistency with werkzeug.
(#698, Stefan Gehn)
- Use npm for package installation.
(#695, Stefan Gehn)
- Use sassc. (Stefan Gehn)
- Cope with broken HTTP clients that require specific casing of
"200 OK". (#646, #347, Konzertheld)
- Add European Portuguese translation. (#692, boturon)
- Various doc updates. (ix5)
- Add Turkish translation. (Özcan Oğuz, #669)
- Drop Python 2 support. (Jelmer Vernooij)
0.12.3 (2020-02-22)
-------------------
- New "flags" option in the [markdown] section to customize Misaka's Markdown
HTML rendering. By default, no flags are set.
[markup]
flags = skip-html, escape, hard-wrap
Check docs/configuration/server.rst for more details. #616
* Fix compatibility with newer versions of werkzeug. #614
* Add Python 3.8 support. #600, #615
* New 'latest' endpoint to serve latest comments. #556
* include admin.js in Python Package. #606
* Add a approve-if-email-previously-approved setting.
* Fall back to author names in gravatars (#482)
* Make Isso compatible with Content Security Policies without `script-src 'unsafe-inline'`. #597
* Set subject for notification about new comment, subject should not be empty. #589
* Fix rendering of disabled.html for 'Sub URI' sites.
* contrib: Add Blogger importer tool. #529
* Return 200 with empty array when there are no comments. #301
* Translation updates for Polish, Slovak, Occitan.
* Redirect to comment after moderation. #358
0.12.2 (2019-01-21)
-------------------
- Revert use of labels instead of placeholders, since it breaks
mail notifications. #524
0.12.1 (2019-01-19)
-------------------
- Revert fix for duplicate slashes, as it prevents isso from
starting in some cases. #523
0.12.0 (2019-01-18)
-------------------
- Fix compatibility with new XML API.
- Don't enable admin interface with default password by default. #491
- Add support and documentation for "generic" imports.
- Remove potential duplicate slashes in URLs from
email links. #420
- Add data-isso-reply-notifications to attributes in configuration.
- Use default IP in imports if none is found. Fixes imports of some comments.
- embed: fix feed link creation on older browsers.
- Properly handle to field in mail notifications when using uWSGI spooler
- css: fix vertical alignment of notification checkbox
0.11.1 (2018-11-03)
-------------------
- Include pre-built minified JavaScript and CSS.
0.11.0 (2018-11-03)
-------------------
Bugs & features:
- Fix link in moderation mails if isso is setup on a sub-url (e.g. domain.tld/comments/)
- Add reply notifications
- Add admin interface
- Add links highlighting in comments
- Add apidoc
- Add rc.d script for FreeBSD
- Add the possibility to set CORS Origin through ISSO_CORS_ORIGIN environ variable
- Add preview button
- Add Atom feed at /feed?uri={thread-id}
- Add optionnal gravatar support
- Add nofollow noopener on links inside comments
- Add Dockerfile
- Upgraded to Misaka 2
- Some tests/travis/documentation improvements and fixes + pep8
Translations:
- Fix Chinese translation & typo in CJK
- Add Danish translation
- Add Hungarian translation
- Add Persian translation
- Improvement on german translation
0.10.6 (2016-09-22)
-------------------
- fix missing configuration field
0.10.5 (2016-09-20)
-------------------
- add support for different vote levels, #260
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg.
`"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given
one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg.
put a star on popular comments).
- add new post preview API endpoint, #254
- add an option for mandatory author, #257
- clients can now use `data-title` to get the HTML title for a new page, #252
- add finish translation and other minor bugfixes
0.10.4 (2016-04-12)
-------------------
- fix wrapper attribute when using data-isso-require-mail="true", #238
- fix reponse for OPTIONS response on Python 3, #242
0.10.3 (2016-02-24)
-------------------
- follow redirects, #193
0.10.2 (2016-02-21)
-------------------
- fix getAttribute return value
0.10.1 (2016-02-06)
-------------------
- fix empty author, email and website values when writing a comment
0.10 (2016-02-06)
-----------------
- add new configuration section for hash handling.
[hash]
salt = Eech7co8Ohloopo9Ol6baimi
algorithm = pbkdf2
You can customize the salt, choose different hash functions and tweak the
parameters for PBKDF2.
- Python 3.4+ validate TLS connections against the system's CA. Previously no
validation was in place, see PEP-446__ for details.
- add `fenced_code` and `no_intra_emphasis` to default configuration.
Fenced code allows to write code without indentation using `~~~` delimiters
(optionally with language identifier).
Intra emphasis would compile `foo_bar_baz` to foo<em>bar</em>baz. This
behavior is very confusing for users not knowing the Markdown spec in detail.
- new configuration to require an email when submitting comments, #199. Set
[guard]
require-email = true
and use `data-isso-require-email="true"` to enable this feature. Disabled by
default.
- new Bulgarian translation by sahwar, new Swedish translation by Gustav
Näslund – #143, new Vietnamese translation by Đinh Xuân Sâm, new Croatian
translation by streger, new Czech translation by Jan Chren
- fix SMTP setup without credentials, #174
- version pin Misaka to 1.x, html5lib to 0.9999999
.. __: https://www.python.org/dev/peps/pep-0466/
0.9.10 (2015-04-11)
-------------------
- fix regression in SMTP authentication, #174
0.9.9 (2015-03-04)
------------------
- several Python 3.x related bugfixes
- don't lose comment form if the server rejected the POST request, #144
- add localStorage fallback if QUOTA_EXCEEDED_ERR is thrown (e.g. Safari
private browsing)
- add '--empty-id' flag to Disqus import, because Disqus' export sucks
- (re)gain compatibility with Werkzeug 0.8 and really old html5lib versions
available in Debian Squeeze, #170 & #168
- add User-Agent when Isso requests the URL, an alternate way to #151 (add
'X-Isso' when requesting).
0.9.8 (2014-10-08)
------------------
- add compatibility with configparser==3.5.0b1, #128
0.9.7 (2014-09-25)
------------------
- fix SMTP authentication using CRAM-MD5 (incorrect usage of
`smtplib`), #126
0.9.6 (2014-08-18)
------------------
- remember name, email and website in localStorage, #119
- add option to hide voting feature, #115
data-isso-vote="true|false"
- remove email field from JSON responses
This is a quite serious issue. For the identicon, an expensive hash is used
to avoid the leakage of personal information like a real email address. A
`git blame` reveals, the email has been unintentionally exposed since the very
first release of Isso :-/
The testsuite now contains a dedicated test to prevent this error in the
future.
0.9.5 (2014-08-10)
------------------
- prevent no-break space ( ) insertion to enable manual line breaks using
two trailing spaces (as per Markdown convention), #112
- limit request size to 256 kb, #107
Previously unlimited or limited by proxy server). 256 kb is a rough
approximation of the next database schema with comments limited to 65535
characters and additional fields.
- add support for logging to file, #103
[general]
log-file =
- show timestamp when hovering <time>, #104
- fix a regression when editing comments with multiple paragraphs introduced
in 0.9.3 which would HTML escape manually inserted linebreaks.
0.9.4 (2014-07-09)
------------------
- fixed a regression when using Isso and Gevent
0.9.3 (2014-07-09)
------------------
- remove scrollIntoView while expanding further comments if a fragment is used
(e.g. #isso-thread brought you back to the top, unexpectedly)
- implement a custom Markdown renderer to support multi-line code listings. The
extension "fenced_code" is now enabled by default and generates HTML
compatible with Highlight.js__.
- escape HTML entities when editing a comment with raw HTML
- fix CSS for input
- remove isso.css from binary distribution to avoid confusion (it's still there
from the very first release, but modifications do not work)
.. __: http://highlightjs.org/
0.9 (2014-05-29)
----------------
- comment pagination by Srijan Choudhary, #15
Isso can now limit the amount of comments shown by default and add link to
show more. By default, all top-level comments are shown but only 5 nested
comments (per reply). You can override the settings:
isso-data-max-comments-top="N"
isso-data-max-comments-nested="N"
Where N is a number from 0 to infinity ("inf"). If you limit the amount of
shown top level comments, the overall comment count may be incorrect and a
known issue.
You can also configure the amount of comments shown per click (5 by default):
isso-data-reveal-on-click="N"
This feature also required a change in the comment structure. Previously, all
comments are stored tree-like but shown linearly. To ease the implementation
of pagination, the comment tree is now limited to a maximum depth of one.
Jeff Atwood explains, why `discussions are flat by design`__.
.. __: http://blog.codinghorror.com/web-discussions-flat-by-design/
When you upgrade, Isso will automatically normalize the tree and some
information gets lost. All new replies to a comment are now automatically a
direct child of the top-level comment.
- style improvements by William Dorffer, #39, #84 #90 and #91
Isso now longer uses a fat SCSS library, but plain CSS instead. The design is
now responsive and no longer sets global CSS rules.
- experimental WordPress import, #75
Isso should be able to import WXR 1.0-1.2 exports. The import code is based
on two WXR dumps I found (and created) and may not work for you. Please
report any failure.
- avatar changes, #49
You can now configure the client to not show avatars:
data-isso-avatar="false"
Also there is no longer an avatar shown next to the comment box. This is due
to the new CSS and removes two runtime dependencies.
- you may now set a full From header, #87
[smtp]
from = Foo Bar <spam@local>
- SMTP (all caps) is now recognized for notifications, #95
- Isso now ships a small demo site at /demo, #44
- a few bugfixes: Disqus import now anonymizes IP addresses, uWSGI spooling for
Python 3, HTTP-Referer fallback for HTTP-Origin
- remove Django's PBKDF2 implementation in favour of the PBKDF2 function
available in werkzeug 0.9 or higher. If you're still using werkzeug 0.8, Isso
imports passlib__ as fallback (if available).
This release also features a new templating engine Jade__ which replaces
Markup.js__. Jade can compile directly to JavaScript with a tiny runtime module
on the client. Along with the removal of sha1.js and pbkdf2.js and a few build
optimizations, the JS client now weighs only 40kb (12kb gzipped) – 52kb resp.
17kb before.
.. __: https://pypi.python.org/pypi/passlib
.. __: http://jade-lang.com/
.. __: https://github.com/adammark/Markup.js
0.8 (2014-03-28)
----------------
- replace ``<textarea>`` with ``<div contentedtiable="true">`` to remove the
sluggish auto-resize on input feature. If you use a custom CSS, replace
``textarea`` with ``.textarea`` and also set ``white-space: pre``.
- remove superscript extension from Markdown defaults as it may lead to
unexpected behavior for certain smileys such as "^^". To enable the extension,
add
[markup]
options = superscript
allowed-elements = sup
to your configuration.
- comment count requests are now bundled into a single POST request, but the old
API is still there (deprecated though).
- store *session-key* in database (once generated on database creation). That
means links to activate, edit or delete comments are now always valid even
when you restart Isso.
Currently statically set session keys in ``[general]`` are automatically
migrated into the database on startup and you will get a notice that you can
remove this option.
- fix undefined timestamp when client time differs for more than 1 second.
The human-readable "time ago" deltas have been refined to match `Moment.js`_
behavior.
- avatar colors and background can now be customized:
* ``data-isso-avatar-bg="#f0f0f0"`` sets the background color
* ``data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."`` sets possible
avatar colors (up to 8 colors are possible).
- new [markup] section to customize Misaka's Markdown generation (strikethrough,
superscript and autolink enabled by default). Furthermore, you can now allow
certain HTML elemenets and attributes in the generated output, e.g. to enable
images, set
[markup]
allowed-elements = img
allowed-attributes = src
Check docs/configuration/server.rst for more details.
- replace requirejs-domready with a (self-made) HTML5 idiom, #51
.. _Moment.js: http://momentjs.com/docs/#/displaying/fromnow/
0.7 (2014-01-29)
----------------
- fix malicious HTML injection (due to wrong API usage). All unknown/unsafe
HTML tags are now removed from the output (`html5lib` 0.99(9) or later) or
properly escaped (older `html5lib` versions).
See 36d702c and 3a1f92b for more details.
- remove kriskowal/q JS library (promises implementation) in favour of a
self-made 50 LoC implementation to ease packaging (for Debian), #51
- add documentation to display a comment counter, #56 and #57
- SMTP notifications now support STARTTLS and use this transport security
by default, #48 and #58. This also changes the configuration option from
`ssl = [yes|no]` to `security = [none|starttls|ssl]`.
- translation can now be made (and updated) with Transifex_. If you want to
take ownership for a language, contact me on IRC.
- fix french pluralform
- the (by default random) session-key is now shown on application startup
to make different keys per startup more visible
- use `threading.lock` by default for systems without semaphore support
.. _Transifex: https://www.transifex.com/projects/p/isso/
0.6 (2013-12-16)
----------------
Major improvements:
- override thread discovery with data-isso-id="...", #27
To use the same thread for different URLs, you can now add a custom
``data-isso-id="my-id"`` attribute which is used to identify and retrieve
comments (defaults to current URL aka `window.location.pathname`).
- `isso.dispatch` now dispatches multiple websites (= configurations) based on
URL prefixes
- fix a cross-site request forgery vulnerability for comment creation, voting,
editing and deletion, #40
- show modal dialog to confirm comment deletion and activation, #36
- new, comprehensive documentation based on reST + Sphinx:
http://posativ.org/docs (or docs/ in the repository). Also includes an
annotated `example.conf`, #43
- new italian and russian translations
Minor improvements:
- move `isso:application` to `isso.run:application` to avoid uneccessary
initialization in some cases (change module if you use uWSGI or Gunicorn)
- add Date header to email notifications, #42
- check for blank text in new comment, #41
- work around IE10's HTML5 abilities for custom data-attributes
- add support for Gunicorn (and other pre-forking WSGI servers)
0.5 (2013-11-17)
----------------
Major improvements:
- `listen` option replaces `host` and `port` to support UNIX domain sockets, #25
Instead of `host = localhost` and `port = 8080`, use
`listen = http://localhost:8080`. To listen on a UNIX domain socket, replace
`http://` with `unix://`, e.g. `unix:///tmp/isso.sock`.
- new option `notify` (in the general section) is used to choose (one or more)
notification backends (currently only SMTP is available, though). Isso will
no longer automatically use SMTP for notifications if the initial connection
succeeds.
- new options to control the client integration
* ``data-isso-css="false"`` prevents the client from appending the CSS to the
document. Enabled by default.
* ``data-isso-lang="de"`` overrides the useragent's preferred language (de, en
and fr are currently supported).
* ``data-isso-reply-to-self="true"`` should be set, when you allow reply to
own comments (see server configuration for details).
- add support for `gevent <http://www.gevent.org/>`_, a coroutine-based Python
networking library that uses greenlets (lightweight threads). Recommended
WSGI server when not running with uWSGI (unfortunately stable gevent is not
yet able to listen on a UNIX domain socket).
- fix a serious issue with the voters bloomfilter. During an Isso run, the
ip addresses from all commenters accumulated into the voters bloomfilter
for new comments. Thus, previous commenters could no longer vote other
comments. This fixes the rare occurences of #5.
In addition to this fix, the current voters bloomfilter will be re-initialized
if you are using Isso 0.4 or below (this is not necessary, but on the
other hand, the current bloomfilter for each comment is sort-of useless).
- french translation (thanks to @sploinga), #38
- support for multiple sites, part of #34
Minor improvements:
- `ipaddr` is now used as `ipaddress` fallback for Python 2.6 and 2.7, #32
- changed URL to activate and delete comments to `/id/<N:int>/activate` etc.
- import command uses `<link>` tag instead of `<id>` to extract the relative
URL path, #37
- import command now uses `isDeleted` to mark comments as deleted (and
eventually remove stale comments). This seems to affect only a few comments
from a previous WordPress import into Disqus.
- import command lists orphaned comments after import.
- import command now has a ``--dry-run`` option to do no actual operation on
the database.
0.4 (2013-11-05)
----------------
- Isso now handles cross-domain requests and cookies, fixes #24
- Isso for Python 2.x now supports werkzeug>=0.8
- limit email length to 254 to avoid Hash-DDoS
- override Isso API location with ``data-isso="..."`` in the script tag
- override HTML title parsing with a custom ``data-title="..."`` attribute
in ``<div id="isso-thread"></div>``
0.3 (2013-11-01)
----------------
- improve initial comment loading performance in the client
- cache slow REST requests, see #18
- add a SQLite trigger that detects and removes stale threads (= threads,
with all comments being removed) from the database when a comment is
removed.
- PyPi releases now include an uncompressed version of the JavaScript
files -- `embed.dev.js` and `count.dev.js` -- to track down errors.
- use uWSGI's internal locking instead of a self-made shared memory lock
0.2 (2013-10-29)
----------------
- initial PyPi release
| Changelog for Isso
==================
%(version)s (%(date)s)
- **BREAKING:** css, js: Prefix all classes with ``isso-`` (#816, ix5)
Now Isso's CSS is "namespaced" in order not to conflict with other classes on
the page.
This change necessitates adjusting custom CSS files to the new names.
- Drop support for outdated Python version 3.5
(#808, l33tname)
- Fix avatar sizing, limit default gravatar images to 55px (#831, l33tname)
In case of a custom gravatar URL, the ``&s=55`` size parameter will have
to be added, see `Gravatar: Image requests`_.
- Add ``data-isso-reply-notifications-default-enabled`` option to configure
whether or not the subscribe to replies checkbox should be checked by default.
- Accessibility: Use labels rather than placeholders for name, email & website
in post box (`#861 <https://github.com/posativ/isso/pull/861>`_, ix5)
- Re-enable ``no-intra-emphasis`` misaka extension in default config.
- Allow ``sup`` and ``sub`` HTML elements by default
- Add ``data-isso-page-author-hashes`` option to client which makes it possible
to style comments and replies made by the page's author(s).
.. _Gravatar: Image requests: http://en.gravatar.com/site/implement/images/
0.12.6 (2022-03-06)
-------------------
- Serve isso.css separately to avoid ``style-src: unsafe-inline`` CSP and allow
clients to override fetch location (#704, ix5):
data-isso-css-url="https://comments.example.org/css/isso.css"
- New "samesite" option in [server] section to override SameSite header for
cookies. (#700, ix5)
- Fallback for SameSite header depending on whether host is served over https
or http (#700, ix5)
- Have client read out shared settings from server. (#311, pellenilsson)
This affects these settings for which ``data-isso-*`` values will be ignored:
[general]
reply-notifications
gravatar
[guard]
reply-to-self
require-author
require-email
- Improved detection of browser-supplied language preferences (#521)
Isso will now honor the newer ``navigator.languages`` global property
as well as ``navigator.language`` and ``navigator.userLanguage``.
There is a new configuration property ``data-isso-default-lang``
that specifies the language to use (instead of English) when none
of these is available. (The existing ``data-isso-lang`` *overrides*
browser-supplied language preferences.)
- Remove ``ISSO_CORS_ORIGIN`` environ variable, which never worked at all
(#803, ix5)
0.12.5 (2021-03-09)
-------------------
- Don't ignore missing configuration files.
(Jelmer Vernooij)
0.12.4 (2021-02-03)
-------------------
- Require Python >= 3.5, for consistency with werkzeug.
(#698, Stefan Gehn)
- Use npm for package installation.
(#695, Stefan Gehn)
- Use sassc. (Stefan Gehn)
- Cope with broken HTTP clients that require specific casing of
"200 OK". (#646, #347, Konzertheld)
- Add European Portuguese translation. (#692, boturon)
- Various doc updates. (ix5)
- Add Turkish translation. (Özcan Oğuz, #669)
- Drop Python 2 support. (Jelmer Vernooij)
0.12.3 (2020-02-22)
-------------------
- New "flags" option in the [markdown] section to customize Misaka's Markdown
HTML rendering. By default, no flags are set.
[markup]
flags = skip-html, escape, hard-wrap
Check docs/configuration/server.rst for more details. #616
* Fix compatibility with newer versions of werkzeug. #614
* Add Python 3.8 support. #600, #615
* New 'latest' endpoint to serve latest comments. #556
* include admin.js in Python Package. #606
* Add a approve-if-email-previously-approved setting.
* Fall back to author names in gravatars (#482)
* Make Isso compatible with Content Security Policies without `script-src 'unsafe-inline'`. #597
* Set subject for notification about new comment, subject should not be empty. #589
* Fix rendering of disabled.html for 'Sub URI' sites.
* contrib: Add Blogger importer tool. #529
* Return 200 with empty array when there are no comments. #301
* Translation updates for Polish, Slovak, Occitan.
* Redirect to comment after moderation. #358
0.12.2 (2019-01-21)
-------------------
- Revert use of labels instead of placeholders, since it breaks
mail notifications. #524
0.12.1 (2019-01-19)
-------------------
- Revert fix for duplicate slashes, as it prevents isso from
starting in some cases. #523
0.12.0 (2019-01-18)
-------------------
- Fix compatibility with new XML API.
- Don't enable admin interface with default password by default. #491
- Add support and documentation for "generic" imports.
- Remove potential duplicate slashes in URLs from
email links. #420
- Add data-isso-reply-notifications to attributes in configuration.
- Use default IP in imports if none is found. Fixes imports of some comments.
- embed: fix feed link creation on older browsers.
- Properly handle to field in mail notifications when using uWSGI spooler
- css: fix vertical alignment of notification checkbox
0.11.1 (2018-11-03)
-------------------
- Include pre-built minified JavaScript and CSS.
0.11.0 (2018-11-03)
-------------------
Bugs & features:
- Fix link in moderation mails if isso is setup on a sub-url (e.g. domain.tld/comments/)
- Add reply notifications
- Add admin interface
- Add links highlighting in comments
- Add apidoc
- Add rc.d script for FreeBSD
- Add the possibility to set CORS Origin through ISSO_CORS_ORIGIN environ variable
- Add preview button
- Add Atom feed at /feed?uri={thread-id}
- Add optionnal gravatar support
- Add nofollow noopener on links inside comments
- Add Dockerfile
- Upgraded to Misaka 2
- Some tests/travis/documentation improvements and fixes + pep8
Translations:
- Fix Chinese translation & typo in CJK
- Add Danish translation
- Add Hungarian translation
- Add Persian translation
- Improvement on german translation
0.10.6 (2016-09-22)
-------------------
- fix missing configuration field
0.10.5 (2016-09-20)
-------------------
- add support for different vote levels, #260
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg.
`"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given
one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg.
put a star on popular comments).
- add new post preview API endpoint, #254
- add an option for mandatory author, #257
- clients can now use `data-title` to get the HTML title for a new page, #252
- add finish translation and other minor bugfixes
0.10.4 (2016-04-12)
-------------------
- fix wrapper attribute when using data-isso-require-mail="true", #238
- fix reponse for OPTIONS response on Python 3, #242
0.10.3 (2016-02-24)
-------------------
- follow redirects, #193
0.10.2 (2016-02-21)
-------------------
- fix getAttribute return value
0.10.1 (2016-02-06)
-------------------
- fix empty author, email and website values when writing a comment
0.10 (2016-02-06)
-----------------
- add new configuration section for hash handling.
[hash]
salt = Eech7co8Ohloopo9Ol6baimi
algorithm = pbkdf2
You can customize the salt, choose different hash functions and tweak the
parameters for PBKDF2.
- Python 3.4+ validate TLS connections against the system's CA. Previously no
validation was in place, see PEP-446__ for details.
- add `fenced_code` and `no_intra_emphasis` to default configuration.
Fenced code allows to write code without indentation using `~~~` delimiters
(optionally with language identifier).
Intra emphasis would compile `foo_bar_baz` to foo<em>bar</em>baz. This
behavior is very confusing for users not knowing the Markdown spec in detail.
- new configuration to require an email when submitting comments, #199. Set
[guard]
require-email = true
and use `data-isso-require-email="true"` to enable this feature. Disabled by
default.
- new Bulgarian translation by sahwar, new Swedish translation by Gustav
Näslund – #143, new Vietnamese translation by Đinh Xuân Sâm, new Croatian
translation by streger, new Czech translation by Jan Chren
- fix SMTP setup without credentials, #174
- version pin Misaka to 1.x, html5lib to 0.9999999
.. __: https://www.python.org/dev/peps/pep-0466/
0.9.10 (2015-04-11)
-------------------
- fix regression in SMTP authentication, #174
0.9.9 (2015-03-04)
------------------
- several Python 3.x related bugfixes
- don't lose comment form if the server rejected the POST request, #144
- add localStorage fallback if QUOTA_EXCEEDED_ERR is thrown (e.g. Safari
private browsing)
- add '--empty-id' flag to Disqus import, because Disqus' export sucks
- (re)gain compatibility with Werkzeug 0.8 and really old html5lib versions
available in Debian Squeeze, #170 & #168
- add User-Agent when Isso requests the URL, an alternate way to #151 (add
'X-Isso' when requesting).
0.9.8 (2014-10-08)
------------------
- add compatibility with configparser==3.5.0b1, #128
0.9.7 (2014-09-25)
------------------
- fix SMTP authentication using CRAM-MD5 (incorrect usage of
`smtplib`), #126
0.9.6 (2014-08-18)
------------------
- remember name, email and website in localStorage, #119
- add option to hide voting feature, #115
data-isso-vote="true|false"
- remove email field from JSON responses
This is a quite serious issue. For the identicon, an expensive hash is used
to avoid the leakage of personal information like a real email address. A
`git blame` reveals, the email has been unintentionally exposed since the very
first release of Isso :-/
The testsuite now contains a dedicated test to prevent this error in the
future.
0.9.5 (2014-08-10)
------------------
- prevent no-break space ( ) insertion to enable manual line breaks using
two trailing spaces (as per Markdown convention), #112
- limit request size to 256 kb, #107
Previously unlimited or limited by proxy server). 256 kb is a rough
approximation of the next database schema with comments limited to 65535
characters and additional fields.
- add support for logging to file, #103
[general]
log-file =
- show timestamp when hovering <time>, #104
- fix a regression when editing comments with multiple paragraphs introduced
in 0.9.3 which would HTML escape manually inserted linebreaks.
0.9.4 (2014-07-09)
------------------
- fixed a regression when using Isso and Gevent
0.9.3 (2014-07-09)
------------------
- remove scrollIntoView while expanding further comments if a fragment is used
(e.g. #isso-thread brought you back to the top, unexpectedly)
- implement a custom Markdown renderer to support multi-line code listings. The
extension "fenced_code" is now enabled by default and generates HTML
compatible with Highlight.js__.
- escape HTML entities when editing a comment with raw HTML
- fix CSS for input
- remove isso.css from binary distribution to avoid confusion (it's still there
from the very first release, but modifications do not work)
.. __: http://highlightjs.org/
0.9 (2014-05-29)
----------------
- comment pagination by Srijan Choudhary, #15
Isso can now limit the amount of comments shown by default and add link to
show more. By default, all top-level comments are shown but only 5 nested
comments (per reply). You can override the settings:
isso-data-max-comments-top="N"
isso-data-max-comments-nested="N"
Where N is a number from 0 to infinity ("inf"). If you limit the amount of
shown top level comments, the overall comment count may be incorrect and a
known issue.
You can also configure the amount of comments shown per click (5 by default):
isso-data-reveal-on-click="N"
This feature also required a change in the comment structure. Previously, all
comments are stored tree-like but shown linearly. To ease the implementation
of pagination, the comment tree is now limited to a maximum depth of one.
Jeff Atwood explains, why `discussions are flat by design`__.
.. __: http://blog.codinghorror.com/web-discussions-flat-by-design/
When you upgrade, Isso will automatically normalize the tree and some
information gets lost. All new replies to a comment are now automatically a
direct child of the top-level comment.
- style improvements by William Dorffer, #39, #84 #90 and #91
Isso now longer uses a fat SCSS library, but plain CSS instead. The design is
now responsive and no longer sets global CSS rules.
- experimental WordPress import, #75
Isso should be able to import WXR 1.0-1.2 exports. The import code is based
on two WXR dumps I found (and created) and may not work for you. Please
report any failure.
- avatar changes, #49
You can now configure the client to not show avatars:
data-isso-avatar="false"
Also there is no longer an avatar shown next to the comment box. This is due
to the new CSS and removes two runtime dependencies.
- you may now set a full From header, #87
[smtp]
from = Foo Bar <spam@local>
- SMTP (all caps) is now recognized for notifications, #95
- Isso now ships a small demo site at /demo, #44
- a few bugfixes: Disqus import now anonymizes IP addresses, uWSGI spooling for
Python 3, HTTP-Referer fallback for HTTP-Origin
- remove Django's PBKDF2 implementation in favour of the PBKDF2 function
available in werkzeug 0.9 or higher. If you're still using werkzeug 0.8, Isso
imports passlib__ as fallback (if available).
This release also features a new templating engine Jade__ which replaces
Markup.js__. Jade can compile directly to JavaScript with a tiny runtime module
on the client. Along with the removal of sha1.js and pbkdf2.js and a few build
optimizations, the JS client now weighs only 40kb (12kb gzipped) – 52kb resp.
17kb before.
.. __: https://pypi.python.org/pypi/passlib
.. __: http://jade-lang.com/
.. __: https://github.com/adammark/Markup.js
0.8 (2014-03-28)
----------------
- replace ``<textarea>`` with ``<div contentedtiable="true">`` to remove the
sluggish auto-resize on input feature. If you use a custom CSS, replace
``textarea`` with ``.textarea`` and also set ``white-space: pre``.
- remove superscript extension from Markdown defaults as it may lead to
unexpected behavior for certain smileys such as "^^". To enable the extension,
add
[markup]
options = superscript
allowed-elements = sup
to your configuration.
- comment count requests are now bundled into a single POST request, but the old
API is still there (deprecated though).
- store *session-key* in database (once generated on database creation). That
means links to activate, edit or delete comments are now always valid even
when you restart Isso.
Currently statically set session keys in ``[general]`` are automatically
migrated into the database on startup and you will get a notice that you can
remove this option.
- fix undefined timestamp when client time differs for more than 1 second.
The human-readable "time ago" deltas have been refined to match `Moment.js`_
behavior.
- avatar colors and background can now be customized:
* ``data-isso-avatar-bg="#f0f0f0"`` sets the background color
* ``data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."`` sets possible
avatar colors (up to 8 colors are possible).
- new [markup] section to customize Misaka's Markdown generation (strikethrough,
superscript and autolink enabled by default). Furthermore, you can now allow
certain HTML elemenets and attributes in the generated output, e.g. to enable
images, set
[markup]
allowed-elements = img
allowed-attributes = src
Check docs/configuration/server.rst for more details.
- replace requirejs-domready with a (self-made) HTML5 idiom, #51
.. _Moment.js: http://momentjs.com/docs/#/displaying/fromnow/
0.7 (2014-01-29)
----------------
- fix malicious HTML injection (due to wrong API usage). All unknown/unsafe
HTML tags are now removed from the output (`html5lib` 0.99(9) or later) or
properly escaped (older `html5lib` versions).
See 36d702c and 3a1f92b for more details.
- remove kriskowal/q JS library (promises implementation) in favour of a
self-made 50 LoC implementation to ease packaging (for Debian), #51
- add documentation to display a comment counter, #56 and #57
- SMTP notifications now support STARTTLS and use this transport security
by default, #48 and #58. This also changes the configuration option from
`ssl = [yes|no]` to `security = [none|starttls|ssl]`.
- translation can now be made (and updated) with Transifex_. If you want to
take ownership for a language, contact me on IRC.
- fix french pluralform
- the (by default random) session-key is now shown on application startup
to make different keys per startup more visible
- use `threading.lock` by default for systems without semaphore support
.. _Transifex: https://www.transifex.com/projects/p/isso/
0.6 (2013-12-16)
----------------
Major improvements:
- override thread discovery with data-isso-id="...", #27
To use the same thread for different URLs, you can now add a custom
``data-isso-id="my-id"`` attribute which is used to identify and retrieve
comments (defaults to current URL aka `window.location.pathname`).
- `isso.dispatch` now dispatches multiple websites (= configurations) based on
URL prefixes
- fix a cross-site request forgery vulnerability for comment creation, voting,
editing and deletion, #40
- show modal dialog to confirm comment deletion and activation, #36
- new, comprehensive documentation based on reST + Sphinx:
http://posativ.org/docs (or docs/ in the repository). Also includes an
annotated `example.conf`, #43
- new italian and russian translations
Minor improvements:
- move `isso:application` to `isso.run:application` to avoid uneccessary
initialization in some cases (change module if you use uWSGI or Gunicorn)
- add Date header to email notifications, #42
- check for blank text in new comment, #41
- work around IE10's HTML5 abilities for custom data-attributes
- add support for Gunicorn (and other pre-forking WSGI servers)
0.5 (2013-11-17)
----------------
Major improvements:
- `listen` option replaces `host` and `port` to support UNIX domain sockets, #25
Instead of `host = localhost` and `port = 8080`, use
`listen = http://localhost:8080`. To listen on a UNIX domain socket, replace
`http://` with `unix://`, e.g. `unix:///tmp/isso.sock`.
- new option `notify` (in the general section) is used to choose (one or more)
notification backends (currently only SMTP is available, though). Isso will
no longer automatically use SMTP for notifications if the initial connection
succeeds.
- new options to control the client integration
* ``data-isso-css="false"`` prevents the client from appending the CSS to the
document. Enabled by default.
* ``data-isso-lang="de"`` overrides the useragent's preferred language (de, en
and fr are currently supported).
* ``data-isso-reply-to-self="true"`` should be set, when you allow reply to
own comments (see server configuration for details).
- add support for `gevent <http://www.gevent.org/>`_, a coroutine-based Python
networking library that uses greenlets (lightweight threads). Recommended
WSGI server when not running with uWSGI (unfortunately stable gevent is not
yet able to listen on a UNIX domain socket).
- fix a serious issue with the voters bloomfilter. During an Isso run, the
ip addresses from all commenters accumulated into the voters bloomfilter
for new comments. Thus, previous commenters could no longer vote other
comments. This fixes the rare occurences of #5.
In addition to this fix, the current voters bloomfilter will be re-initialized
if you are using Isso 0.4 or below (this is not necessary, but on the
other hand, the current bloomfilter for each comment is sort-of useless).
- french translation (thanks to @sploinga), #38
- support for multiple sites, part of #34
Minor improvements:
- `ipaddr` is now used as `ipaddress` fallback for Python 2.6 and 2.7, #32
- changed URL to activate and delete comments to `/id/<N:int>/activate` etc.
- import command uses `<link>` tag instead of `<id>` to extract the relative
URL path, #37
- import command now uses `isDeleted` to mark comments as deleted (and
eventually remove stale comments). This seems to affect only a few comments
from a previous WordPress import into Disqus.
- import command lists orphaned comments after import.
- import command now has a ``--dry-run`` option to do no actual operation on
the database.
0.4 (2013-11-05)
----------------
- Isso now handles cross-domain requests and cookies, fixes #24
- Isso for Python 2.x now supports werkzeug>=0.8
- limit email length to 254 to avoid Hash-DDoS
- override Isso API location with ``data-isso="..."`` in the script tag
- override HTML title parsing with a custom ``data-title="..."`` attribute
in ``<div id="isso-thread"></div>``
0.3 (2013-11-01)
----------------
- improve initial comment loading performance in the client
- cache slow REST requests, see #18
- add a SQLite trigger that detects and removes stale threads (= threads,
with all comments being removed) from the database when a comment is
removed.
- PyPi releases now include an uncompressed version of the JavaScript
files -- `embed.dev.js` and `count.dev.js` -- to track down errors.
- use uWSGI's internal locking instead of a self-made shared memory lock
0.2 (2013-10-29)
----------------
- initial PyPi release
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | `reST` requires double backticks (\`\`data-isso-...\`\`) around code instead of markdown's one. | ix5 | 30 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | docs/docs/reference/client-config.rst | Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
data-isso-reply-notifications-default-enabled="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Overriding translation strings
------------------------------
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
.. code-block:: html
data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
data-isso-* directives
------------------------
data-isso
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
Always render the Isso UI in this language, ignoring what the
user-agent says is the preferred language. The default is to
honor the user-agent's preferred language, and this can be
specified explicitly by using ``data-isso-lang=""``.
The value of this property should be a `BCP 47 language tag
<https://tools.ietf.org/html/bcp47>`_, such as "en", "ru", or "pt-BR".
Language tags are processed case-insensitively, and may use
underscores as separators instead of dashes (e.g. "pt_br" is treated
the same as same as "pt-BR").
You can find a list of all supported languages by browsing the
`i18n directory
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_ of
the source tree.
data-isso-default-lang
Render the Isso UI in this language when the user-agent does not
specify a preferred language, or if the language it specifies is not
supported. Like ``data-isso-lang``, the value of this property should
be a BCP 47 language tag. Defaults to "en".
If you specify both ``data-isso-default-lang`` and ``data-isso-lang``,
``data-isso-lang`` takes precedence.
.. versionadded:: 0.12.6
data-isso-max-comments-top, data-isso-max-comments-nested
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to ``"inf"`` to show all, or ``"0"`` to hide all.
data-isso-reveal-on-click
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
Enable or disable avatar generation. Ignored if gravatar is enabled on
server side, since gravatars will take precedence and disable avatar
generation.
data-isso-avatar-bg
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-vote
Enable or disable voting feature on the client side.
data-isso-vote-levels
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
data-isso-reply-notifications-default-enabled
Set to ``true`` to make the reply notifications checkbox on the postbox be
checked by default. Otherwise, the user will have to manually opt-in to
reply notifications.
This setting will have no effect if ``reply-notifications`` are not enabled
on the server.
Default: ``false``
.. versionadded:: 0.13
Deprecated Client Settings
--------------------------
In earlier versions the following settings had to mirror the
corresponding settings in the server configuration, but they are now
read out from the server automatically.
data-isso-reply-to-self
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
.. deprecated:: 0.12.6
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-gravatar
.. deprecated:: 0.12.6
Set to `true` when gravatars are enabled with `gravatar = true` in the
server configuration.
| Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
data-isso-page-author-hashes="f124cf6b2f01,7831fe17a8cd"
data-isso-reply-notifications-default-enabled="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Overriding translation strings
------------------------------
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
.. code-block:: html
data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
data-isso-* directives
------------------------
data-isso
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
Always render the Isso UI in this language, ignoring what the
user-agent says is the preferred language. The default is to
honor the user-agent's preferred language, and this can be
specified explicitly by using ``data-isso-lang=""``.
The value of this property should be a `BCP 47 language tag
<https://tools.ietf.org/html/bcp47>`_, such as "en", "ru", or "pt-BR".
Language tags are processed case-insensitively, and may use
underscores as separators instead of dashes (e.g. "pt_br" is treated
the same as same as "pt-BR").
You can find a list of all supported languages by browsing the
`i18n directory
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_ of
the source tree.
data-isso-default-lang
Render the Isso UI in this language when the user-agent does not
specify a preferred language, or if the language it specifies is not
supported. Like ``data-isso-lang``, the value of this property should
be a BCP 47 language tag. Defaults to "en".
If you specify both ``data-isso-default-lang`` and ``data-isso-lang``,
``data-isso-lang`` takes precedence.
.. versionadded:: 0.12.6
data-isso-max-comments-top, data-isso-max-comments-nested
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to ``"inf"`` to show all, or ``"0"`` to hide all.
data-isso-reveal-on-click
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
Enable or disable avatar generation. Ignored if gravatar is enabled on
server side, since gravatars will take precedence and disable avatar
generation.
data-isso-avatar-bg
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-vote
Enable or disable voting feature on the client side.
data-isso-vote-levels
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
data-isso-page-author-hashes
Provide the hash (or list of hashes) of the current page's author. Any
comments made by those authors will be given the ``isso-is-page-author``
class. This can be styled using CSS.
The hash of a user can be found by checking the ``data-hash`` parameter on the
``<div>`` tag containing their comment. This is what the element looks like:
.. code-block:: html
<div class="isso-comment isso-no-votes" id="isso-14" data-hash="41faef0a49fc">
According to this example, your script tag would look something like this:
.. code-block:: html
<script src="..." data-isso-page-author-hashes="41faef0a49fc"></script>
When adding multiple hashes to support multiple page authors, separate the
hashes by a command and/or space. All of the following are acceptable
(although the hashes are made up):
- ``data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"``
- ``data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"``
- ``data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"``
For example, these CSS rules make the page author's name a sort of
turquoise color, and the comment's background a lighter version of that:
.. code-block:: css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
.. versionadded:: 0.13
data-isso-reply-notifications-default-enabled
Set to ``true`` to make the reply notifications checkbox on the postbox be
checked by default. Otherwise, the user will have to manually opt-in to
reply notifications.
This setting will have no effect if ``reply-notifications`` are not enabled
on the server.
Default: ``false``
.. versionadded:: 0.13
Deprecated Client Settings
--------------------------
In earlier versions the following settings had to mirror the
corresponding settings in the server configuration, but they are now
read out from the server automatically.
data-isso-reply-to-self
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
.. deprecated:: 0.12.6
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-gravatar
.. deprecated:: 0.12.6
Set to `true` when gravatars are enabled with `gravatar = true` in the
server configuration.
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | Well done, very nicely documented!
Note to myself: The specifics of this should probably be moved into the "Tips & Tricks" section. I'll do that afterwards, not part of this PR.
Also, a script to derive the hashes should be added to contrib or as a CLI option that takes `salt` and other set options into account (also by me):
```python
import codecs
from hashlib import pbkdf2_hmac as pbkdf2
val = "email@email.com".encode("utf-8") # change me!
salt = b"Eech7co8Ohloopo9Ol6baimi"
iterations = 1000
dklen = 6
func = "sha1"
compute = pbkdf2(
hash_name=func,
password=val,
salt=salt,
iterations=iterations,
dklen=dklen
)
hash_ = compute
uhash = codecs.encode(hash_, "hex_codec").decode("utf-8")
print("uhash: %s" % uhash)
``` | ix5 | 31 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | docs/docs/reference/client-config.rst | Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
data-isso-reply-notifications-default-enabled="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Overriding translation strings
------------------------------
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
.. code-block:: html
data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
data-isso-* directives
------------------------
data-isso
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
Always render the Isso UI in this language, ignoring what the
user-agent says is the preferred language. The default is to
honor the user-agent's preferred language, and this can be
specified explicitly by using ``data-isso-lang=""``.
The value of this property should be a `BCP 47 language tag
<https://tools.ietf.org/html/bcp47>`_, such as "en", "ru", or "pt-BR".
Language tags are processed case-insensitively, and may use
underscores as separators instead of dashes (e.g. "pt_br" is treated
the same as same as "pt-BR").
You can find a list of all supported languages by browsing the
`i18n directory
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_ of
the source tree.
data-isso-default-lang
Render the Isso UI in this language when the user-agent does not
specify a preferred language, or if the language it specifies is not
supported. Like ``data-isso-lang``, the value of this property should
be a BCP 47 language tag. Defaults to "en".
If you specify both ``data-isso-default-lang`` and ``data-isso-lang``,
``data-isso-lang`` takes precedence.
.. versionadded:: 0.12.6
data-isso-max-comments-top, data-isso-max-comments-nested
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to ``"inf"`` to show all, or ``"0"`` to hide all.
data-isso-reveal-on-click
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
Enable or disable avatar generation. Ignored if gravatar is enabled on
server side, since gravatars will take precedence and disable avatar
generation.
data-isso-avatar-bg
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-vote
Enable or disable voting feature on the client side.
data-isso-vote-levels
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
data-isso-reply-notifications-default-enabled
Set to ``true`` to make the reply notifications checkbox on the postbox be
checked by default. Otherwise, the user will have to manually opt-in to
reply notifications.
This setting will have no effect if ``reply-notifications`` are not enabled
on the server.
Default: ``false``
.. versionadded:: 0.13
Deprecated Client Settings
--------------------------
In earlier versions the following settings had to mirror the
corresponding settings in the server configuration, but they are now
read out from the server automatically.
data-isso-reply-to-self
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
.. deprecated:: 0.12.6
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-gravatar
.. deprecated:: 0.12.6
Set to `true` when gravatars are enabled with `gravatar = true` in the
server configuration.
| Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
data-isso-page-author-hashes="f124cf6b2f01,7831fe17a8cd"
data-isso-reply-notifications-default-enabled="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Overriding translation strings
------------------------------
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
.. code-block:: html
data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
data-isso-* directives
------------------------
data-isso
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
Always render the Isso UI in this language, ignoring what the
user-agent says is the preferred language. The default is to
honor the user-agent's preferred language, and this can be
specified explicitly by using ``data-isso-lang=""``.
The value of this property should be a `BCP 47 language tag
<https://tools.ietf.org/html/bcp47>`_, such as "en", "ru", or "pt-BR".
Language tags are processed case-insensitively, and may use
underscores as separators instead of dashes (e.g. "pt_br" is treated
the same as same as "pt-BR").
You can find a list of all supported languages by browsing the
`i18n directory
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_ of
the source tree.
data-isso-default-lang
Render the Isso UI in this language when the user-agent does not
specify a preferred language, or if the language it specifies is not
supported. Like ``data-isso-lang``, the value of this property should
be a BCP 47 language tag. Defaults to "en".
If you specify both ``data-isso-default-lang`` and ``data-isso-lang``,
``data-isso-lang`` takes precedence.
.. versionadded:: 0.12.6
data-isso-max-comments-top, data-isso-max-comments-nested
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to ``"inf"`` to show all, or ``"0"`` to hide all.
data-isso-reveal-on-click
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
Enable or disable avatar generation. Ignored if gravatar is enabled on
server side, since gravatars will take precedence and disable avatar
generation.
data-isso-avatar-bg
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-vote
Enable or disable voting feature on the client side.
data-isso-vote-levels
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
data-isso-page-author-hashes
Provide the hash (or list of hashes) of the current page's author. Any
comments made by those authors will be given the ``isso-is-page-author``
class. This can be styled using CSS.
The hash of a user can be found by checking the ``data-hash`` parameter on the
``<div>`` tag containing their comment. This is what the element looks like:
.. code-block:: html
<div class="isso-comment isso-no-votes" id="isso-14" data-hash="41faef0a49fc">
According to this example, your script tag would look something like this:
.. code-block:: html
<script src="..." data-isso-page-author-hashes="41faef0a49fc"></script>
When adding multiple hashes to support multiple page authors, separate the
hashes by a command and/or space. All of the following are acceptable
(although the hashes are made up):
- ``data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"``
- ``data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"``
- ``data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"``
For example, these CSS rules make the page author's name a sort of
turquoise color, and the comment's background a lighter version of that:
.. code-block:: css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
.. versionadded:: 0.13
data-isso-reply-notifications-default-enabled
Set to ``true`` to make the reply notifications checkbox on the postbox be
checked by default. Otherwise, the user will have to manually opt-in to
reply notifications.
This setting will have no effect if ``reply-notifications`` are not enabled
on the server.
Default: ``false``
.. versionadded:: 0.13
Deprecated Client Settings
--------------------------
In earlier versions the following settings had to mirror the
corresponding settings in the server configuration, but they are now
read out from the server automatically.
data-isso-reply-to-self
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
.. deprecated:: 0.12.6
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-gravatar
.. deprecated:: 0.12.6
Set to `true` when gravatars are enabled with `gravatar = true` in the
server configuration.
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | Do I need to add that script or will you do it in another commit? And also is there anything else that needs to be modified in this PR? | BBaoVanC | 32 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | docs/docs/reference/client-config.rst | Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
data-isso-reply-notifications-default-enabled="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Overriding translation strings
------------------------------
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
.. code-block:: html
data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
data-isso-* directives
------------------------
data-isso
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
Always render the Isso UI in this language, ignoring what the
user-agent says is the preferred language. The default is to
honor the user-agent's preferred language, and this can be
specified explicitly by using ``data-isso-lang=""``.
The value of this property should be a `BCP 47 language tag
<https://tools.ietf.org/html/bcp47>`_, such as "en", "ru", or "pt-BR".
Language tags are processed case-insensitively, and may use
underscores as separators instead of dashes (e.g. "pt_br" is treated
the same as same as "pt-BR").
You can find a list of all supported languages by browsing the
`i18n directory
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_ of
the source tree.
data-isso-default-lang
Render the Isso UI in this language when the user-agent does not
specify a preferred language, or if the language it specifies is not
supported. Like ``data-isso-lang``, the value of this property should
be a BCP 47 language tag. Defaults to "en".
If you specify both ``data-isso-default-lang`` and ``data-isso-lang``,
``data-isso-lang`` takes precedence.
.. versionadded:: 0.12.6
data-isso-max-comments-top, data-isso-max-comments-nested
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to ``"inf"`` to show all, or ``"0"`` to hide all.
data-isso-reveal-on-click
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
Enable or disable avatar generation. Ignored if gravatar is enabled on
server side, since gravatars will take precedence and disable avatar
generation.
data-isso-avatar-bg
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-vote
Enable or disable voting feature on the client side.
data-isso-vote-levels
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
data-isso-reply-notifications-default-enabled
Set to ``true`` to make the reply notifications checkbox on the postbox be
checked by default. Otherwise, the user will have to manually opt-in to
reply notifications.
This setting will have no effect if ``reply-notifications`` are not enabled
on the server.
Default: ``false``
.. versionadded:: 0.13
Deprecated Client Settings
--------------------------
In earlier versions the following settings had to mirror the
corresponding settings in the server configuration, but they are now
read out from the server automatically.
data-isso-reply-to-self
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
.. deprecated:: 0.12.6
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-gravatar
.. deprecated:: 0.12.6
Set to `true` when gravatars are enabled with `gravatar = true` in the
server configuration.
| Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
data-isso-page-author-hashes="f124cf6b2f01,7831fe17a8cd"
data-isso-reply-notifications-default-enabled="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Overriding translation strings
------------------------------
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
.. code-block:: html
data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
data-isso-* directives
------------------------
data-isso
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
Always render the Isso UI in this language, ignoring what the
user-agent says is the preferred language. The default is to
honor the user-agent's preferred language, and this can be
specified explicitly by using ``data-isso-lang=""``.
The value of this property should be a `BCP 47 language tag
<https://tools.ietf.org/html/bcp47>`_, such as "en", "ru", or "pt-BR".
Language tags are processed case-insensitively, and may use
underscores as separators instead of dashes (e.g. "pt_br" is treated
the same as same as "pt-BR").
You can find a list of all supported languages by browsing the
`i18n directory
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_ of
the source tree.
data-isso-default-lang
Render the Isso UI in this language when the user-agent does not
specify a preferred language, or if the language it specifies is not
supported. Like ``data-isso-lang``, the value of this property should
be a BCP 47 language tag. Defaults to "en".
If you specify both ``data-isso-default-lang`` and ``data-isso-lang``,
``data-isso-lang`` takes precedence.
.. versionadded:: 0.12.6
data-isso-max-comments-top, data-isso-max-comments-nested
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to ``"inf"`` to show all, or ``"0"`` to hide all.
data-isso-reveal-on-click
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
Enable or disable avatar generation. Ignored if gravatar is enabled on
server side, since gravatars will take precedence and disable avatar
generation.
data-isso-avatar-bg
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-vote
Enable or disable voting feature on the client side.
data-isso-vote-levels
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
data-isso-page-author-hashes
Provide the hash (or list of hashes) of the current page's author. Any
comments made by those authors will be given the ``isso-is-page-author``
class. This can be styled using CSS.
The hash of a user can be found by checking the ``data-hash`` parameter on the
``<div>`` tag containing their comment. This is what the element looks like:
.. code-block:: html
<div class="isso-comment isso-no-votes" id="isso-14" data-hash="41faef0a49fc">
According to this example, your script tag would look something like this:
.. code-block:: html
<script src="..." data-isso-page-author-hashes="41faef0a49fc"></script>
When adding multiple hashes to support multiple page authors, separate the
hashes by a command and/or space. All of the following are acceptable
(although the hashes are made up):
- ``data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"``
- ``data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"``
- ``data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"``
For example, these CSS rules make the page author's name a sort of
turquoise color, and the comment's background a lighter version of that:
.. code-block:: css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
.. versionadded:: 0.13
data-isso-reply-notifications-default-enabled
Set to ``true`` to make the reply notifications checkbox on the postbox be
checked by default. Otherwise, the user will have to manually opt-in to
reply notifications.
This setting will have no effect if ``reply-notifications`` are not enabled
on the server.
Default: ``false``
.. versionadded:: 0.13
Deprecated Client Settings
--------------------------
In earlier versions the following settings had to mirror the
corresponding settings in the server configuration, but they are now
read out from the server automatically.
data-isso-reply-to-self
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
.. deprecated:: 0.12.6
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-gravatar
.. deprecated:: 0.12.6
Set to `true` when gravatars are enabled with `gravatar = true` in the
server configuration.
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | I'll add that script later. Apart from the missing `.isso-page-author-suffix` styles I mentioned inline, I think this should be good to go.
All in all, this PR is a good one - I know that having a proper user management would ofc be the better option, but within the restrictions of the current project status, this is what makes most sense. | ix5 | 33 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | docs/docs/reference/client-config.rst | Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
data-isso-reply-notifications-default-enabled="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Overriding translation strings
------------------------------
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
.. code-block:: html
data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
data-isso-* directives
------------------------
data-isso
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
Always render the Isso UI in this language, ignoring what the
user-agent says is the preferred language. The default is to
honor the user-agent's preferred language, and this can be
specified explicitly by using ``data-isso-lang=""``.
The value of this property should be a `BCP 47 language tag
<https://tools.ietf.org/html/bcp47>`_, such as "en", "ru", or "pt-BR".
Language tags are processed case-insensitively, and may use
underscores as separators instead of dashes (e.g. "pt_br" is treated
the same as same as "pt-BR").
You can find a list of all supported languages by browsing the
`i18n directory
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_ of
the source tree.
data-isso-default-lang
Render the Isso UI in this language when the user-agent does not
specify a preferred language, or if the language it specifies is not
supported. Like ``data-isso-lang``, the value of this property should
be a BCP 47 language tag. Defaults to "en".
If you specify both ``data-isso-default-lang`` and ``data-isso-lang``,
``data-isso-lang`` takes precedence.
.. versionadded:: 0.12.6
data-isso-max-comments-top, data-isso-max-comments-nested
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to ``"inf"`` to show all, or ``"0"`` to hide all.
data-isso-reveal-on-click
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
Enable or disable avatar generation. Ignored if gravatar is enabled on
server side, since gravatars will take precedence and disable avatar
generation.
data-isso-avatar-bg
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-vote
Enable or disable voting feature on the client side.
data-isso-vote-levels
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
data-isso-reply-notifications-default-enabled
Set to ``true`` to make the reply notifications checkbox on the postbox be
checked by default. Otherwise, the user will have to manually opt-in to
reply notifications.
This setting will have no effect if ``reply-notifications`` are not enabled
on the server.
Default: ``false``
.. versionadded:: 0.13
Deprecated Client Settings
--------------------------
In earlier versions the following settings had to mirror the
corresponding settings in the server configuration, but they are now
read out from the server automatically.
data-isso-reply-to-self
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
.. deprecated:: 0.12.6
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-gravatar
.. deprecated:: 0.12.6
Set to `true` when gravatars are enabled with `gravatar = true` in the
server configuration.
| Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
data-isso-page-author-hashes="f124cf6b2f01,7831fe17a8cd"
data-isso-reply-notifications-default-enabled="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Overriding translation strings
------------------------------
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
.. code-block:: html
data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
data-isso-* directives
------------------------
data-isso
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
Always render the Isso UI in this language, ignoring what the
user-agent says is the preferred language. The default is to
honor the user-agent's preferred language, and this can be
specified explicitly by using ``data-isso-lang=""``.
The value of this property should be a `BCP 47 language tag
<https://tools.ietf.org/html/bcp47>`_, such as "en", "ru", or "pt-BR".
Language tags are processed case-insensitively, and may use
underscores as separators instead of dashes (e.g. "pt_br" is treated
the same as same as "pt-BR").
You can find a list of all supported languages by browsing the
`i18n directory
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_ of
the source tree.
data-isso-default-lang
Render the Isso UI in this language when the user-agent does not
specify a preferred language, or if the language it specifies is not
supported. Like ``data-isso-lang``, the value of this property should
be a BCP 47 language tag. Defaults to "en".
If you specify both ``data-isso-default-lang`` and ``data-isso-lang``,
``data-isso-lang`` takes precedence.
.. versionadded:: 0.12.6
data-isso-max-comments-top, data-isso-max-comments-nested
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to ``"inf"`` to show all, or ``"0"`` to hide all.
data-isso-reveal-on-click
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
Enable or disable avatar generation. Ignored if gravatar is enabled on
server side, since gravatars will take precedence and disable avatar
generation.
data-isso-avatar-bg
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-vote
Enable or disable voting feature on the client side.
data-isso-vote-levels
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
data-isso-page-author-hashes
Provide the hash (or list of hashes) of the current page's author. Any
comments made by those authors will be given the ``isso-is-page-author``
class. This can be styled using CSS.
The hash of a user can be found by checking the ``data-hash`` parameter on the
``<div>`` tag containing their comment. This is what the element looks like:
.. code-block:: html
<div class="isso-comment isso-no-votes" id="isso-14" data-hash="41faef0a49fc">
According to this example, your script tag would look something like this:
.. code-block:: html
<script src="..." data-isso-page-author-hashes="41faef0a49fc"></script>
When adding multiple hashes to support multiple page authors, separate the
hashes by a command and/or space. All of the following are acceptable
(although the hashes are made up):
- ``data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"``
- ``data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"``
- ``data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"``
For example, these CSS rules make the page author's name a sort of
turquoise color, and the comment's background a lighter version of that:
.. code-block:: css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
.. versionadded:: 0.13
data-isso-reply-notifications-default-enabled
Set to ``true`` to make the reply notifications checkbox on the postbox be
checked by default. Otherwise, the user will have to manually opt-in to
reply notifications.
This setting will have no effect if ``reply-notifications`` are not enabled
on the server.
Default: ``false``
.. versionadded:: 0.13
Deprecated Client Settings
--------------------------
In earlier versions the following settings had to mirror the
corresponding settings in the server configuration, but they are now
read out from the server automatically.
data-isso-reply-to-self
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
.. deprecated:: 0.12.6
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
.. deprecated:: 0.12.6
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-gravatar
.. deprecated:: 0.12.6
Set to `true` when gravatars are enabled with `gravatar = true` in the
server configuration.
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | The `.isso-page-author-suffix` style has been added in 63d2198ea2e7fe1c70fa44f3a240d832b4865abf. | BBaoVanC | 34 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | Please don't use `!important`, either make the selector more specific or fix the underlying issue. | ix5 | 35 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | How did you arrive at that specific color? Will it also look good on dark background? | ix5 | 36 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | I used a color picker to get roughly the same hue as the link color (on the reply button), and then I lightened and desaturated it.
As for it working on a dark background, it doesn't really fit. However, it looked to me that the rest of the CSS doesn't really plan for a dark background by default either. The background color of the postbox fields and the preview field are set to be very light colors which doesn't fit in on a dark background. Since the text color isn't overridden inside the preview box, it becomes white text on a light background if the outer site is set to have white text on black background. Additionally, the text color when hovering over links in (such as the reply button) is very dark, making it hard to read. A lot of these colors need to be overridden to work well on a dark background.
![reply text hovering on black background](https://user-images.githubusercontent.com/17971474/165407732-d95c5d7e-31ca-4d4a-9c7b-c7e53dc835bd.png)
![white text on light background with preview](https://user-images.githubusercontent.com/17971474/165407789-bebaa1c0-ec5b-4984-a410-423f2d1e0091.png)
| BBaoVanC | 37 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | To be honest, maybe don't include any style changes in this PR then and let users decide.
For instance, I'm using this and would have to tweak my CSS to override the default styling that this PR introduces:
![Screenshot from 2022-04-27 01-38-55](https://user-images.githubusercontent.com/10212877/165410002-98018d4e-3720-4616-8f01-0e7b7878d06b.png)
| ix5 | 38 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | Also, there should be some kind of textual indication for blind/impaired users instead of a purely visual one.
![Screenshot from 2022-04-27 01-41-56](https://user-images.githubusercontent.com/10212877/165410242-c6637e2e-81f9-44d5-a94d-612adbfee992.png)
The `(Author)` text should then be part of `isso/js/app/i18n/en.js` as e.g.
`"postbox-page-author": "(Author)" // or "(Site owner)"` | ix5 | 39 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | > To be honest, maybe don't include any style changes in this PR then and let users decide.
>
> For instance, I'm using this and would have to tweak my CSS to override the default styling that this PR introduces: ![Screenshot from 2022-04-27 01-38-55](https://user-images.githubusercontent.com/10212877/165410002-98018d4e-3720-4616-8f01-0e7b7878d06b.png)
I think the commits I just pushed a few minutes ago fixes that due to a [small refactor I did](https://github.com/posativ/isso/compare/0b64ba1866d24b66b0feee2126a016cbac2969b2..a85c85ea159db5f585f6bd9d1e4b08a5e7370ab2?diff=split#diff-c20d9e95fdd0eb015d78774a734e4b2b708656bb788869a2d46140d8d7f152b1).
And I guess I can just take those colors out and instead put them somewhere in the docs anyways. | BBaoVanC | 40 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | I hope you're not waiting on feedback from my end.
For now, let's leave out the background color changes (also, those might clash with the highlight-linked-comment PR?).
To gather screenshots, you can use the pre-packaged demo site. Run `isso -c share/isso-dev.cfg run` and visit `localhost:8080/demo`. Edit `isso/demo/index.html` to add the author badge `data-isso-` attribute. | ix5 | 41 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | > I hope you're not waiting on feedback from my end.
>
> For now, let's leave out the background color changes (also, those might clash with the highlight-linked-comment PR?).
>
> To gather screenshots, you can use the pre-packaged demo site. Run `isso -c share/isso-dev.cfg run` and visit `localhost:8080/demo`. Edit `isso/demo/index.html` to add the author badge `data-isso-` attribute.
Yeah I wasn't waiting for anything, I've just been putting it off because of other projects I'm working on, and school. I can probably finish this tomorrow though, if not today. | BBaoVanC | 42 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | This commit is titled `css: isso.css: Implement styling for .isso-is-page-author` but it does not add any styling to `.isso-is-page-author`.
Here's what makes most sense: Style the `.isso-page-author-suffix` class:
```css
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
```
Bold font weight to match author class and color is author color `#555` slightly darkened. | ix5 | 43 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/css/isso.css | #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
padding-top: 0.95em;
margin: 0.95em auto;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 3px 15px 0 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| #isso-thread * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#isso-thread .isso-comment-header a {
text-decoration: none;
}
#isso-thread {
padding: 0;
margin: 0;
}
#isso-thread > h4 {
color: #555;
font-weight: bold;
}
#isso-thread > .isso-feedlink {
float: right;
padding-left: 1em;
}
#isso-thread > .isso-feedlink > a {
font-size: 0.8em;
vertical-align: bottom;
}
#isso-thread .isso-textarea {
min-height: 58px;
outline: 0;
}
#isso-thread .isso-textarea.isso-placeholder {
color: #757575;
}
#isso-root .isso-comment {
max-width: 68em;
}
#isso-root .isso-preview .isso-comment {
padding-top: 0;
margin: 0;
}
#isso-root .isso-comment:not(:first-of-type),
.isso-follow-up .isso-comment {
border-top: 1px solid rgba(0, 0, 0, 0.1);
margin-bottom: 0.5em;
}
.isso-comment > .isso-avatar {
display: block;
float: left;
margin: 0.95em 0.95em 0;
}
.isso-comment > .isso-avatar > svg {
max-width: 48px;
max-height: 48px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-comment > .isso-text-wrapper {
display: block;
padding: 0.95em;
}
.isso-comment .isso-follow-up {
padding-left: calc(7% + 20px);
}
.isso-comment > .isso-text-wrapper > .isso-comment-header, .isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.95em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header {
font-size: 0.85em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer {
padding: 0 6px;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent {
color: gray !important;
font-weight: normal;
text-shadow: none !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-spacer:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-permalink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-header a.isso-parent:hover {
color: #606060 !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-note {
float: right;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-author {
font-weight: bold;
color: #555;
}
.isso-comment > .isso-text-wrapper > .isso-comment-header .isso-page-author-suffix {
font-weight: bold;
color: #2c2c2c;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p {
margin-top: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text p:last-child {
margin-bottom: 0.2em;
}
.isso-comment > .isso-text-wrapper > .isso-text h1,
.isso-comment > .isso-text-wrapper > .isso-text h2,
.isso-comment > .isso-text-wrapper > .isso-text h3,
.isso-comment > .isso-text-wrapper > .isso-text h4,
.isso-comment > .isso-text-wrapper > .isso-text h5,
.isso-comment > .isso-text-wrapper > .isso-text h6 {
font-size: 130%;
font-weight: bold;
}
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-textarea,
.isso-comment > .isso-text-wrapper > .isso-textarea-wrapper .isso-preview {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 2px;
box-shadow: 0 0 2px #888;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer {
font-size: 0.80em;
color: gray !important;
clear: left;
}
.isso-feedlink,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a {
font-weight: bold;
text-decoration: none;
}
.isso-feedlink:hover,
.isso-comment > .isso-text-wrapper > .isso-comment-footer a:hover {
color: #111111 !important;
text-shadow: #aaaaaa 0 0 1px !important;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a {
position: relative;
top: .2em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer > a + a {
padding-left: 1em;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-votes {
color: gray;
}
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-upvote svg,
.isso-comment > .isso-text-wrapper > .isso-comment-footer .isso-downvote svg {
position: relative;
top: .2em;
}
.isso-comment .isso-postbox {
margin-top: 0.8em;
}
.isso-comment.isso-no-votes > * > .isso-comment-footer span.isso-votes {
display: none;
}
.isso-postbox {
max-width: 68em;
margin: 0 auto 2em;
clear: right;
}
.isso-postbox > .isso-form-wrapper {
display: block;
padding: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section,
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
}
.isso-postbox > .isso-form-wrapper .isso-textarea,
.isso-postbox > .isso-form-wrapper .isso-preview {
margin: 0 0 .3em;
padding: .4em .8em;
border-radius: 3px;
background-color: #fff;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper input[type=checkbox] {
vertical-align: middle;
position: relative;
bottom: 1px;
margin-left: 0;
}
.isso-postbox > .isso-form-wrapper .isso-notification-section {
font-size: 0.90em;
padding-top: .3em;
}
#isso-thread .isso-textarea:focus,
#isso-thread input:focus {
border-color: rgba(0, 0, 0, 0.8);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: inline-block;
position: relative;
max-width: 25%;
margin: 0;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
padding: .3em 10px;
max-width: 100%;
border-radius: 3px;
background-color: #fff;
line-height: 1.4em;
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper label {
display: inline-block;
line-height: 1.4em;
height: 1.4em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
display: block;
float: right;
margin: 1.4em 0 0 5px;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input {
padding: calc(.3em - 1px);
border-radius: 2px;
border: 1px solid #CCC;
background-color: #DDD;
cursor: pointer;
outline: 0;
line-height: 1.4em;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:hover {
background-color: #CCC;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action > input:active {
background-color: #BBB;
}
.isso-postbox > .isso-form-wrapper .isso-preview,
.isso-postbox > .isso-form-wrapper input[name="edit"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="preview"],
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-textarea {
display: none;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper .isso-preview {
display: block;
}
.isso-postbox.isso-preview-mode > .isso-form-wrapper input[name="edit"] {
display: inline;
}
.isso-postbox > .isso-form-wrapper .isso-preview {
background-color: #f8f8f8;
background: repeating-linear-gradient(
-45deg,
#f8f8f8,
#f8f8f8 10px,
#fff 10px,
#fff 20px
);
}
.isso-postbox > .isso-form-wrapper > .isso-notification-section {
display: none;
padding-bottom: 10px;
}
@media screen and (max-width:600px) {
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper {
display: block;
max-width: 100%;
margin: 0 0 .3em;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-input-wrapper input {
width: 100%;
}
.isso-postbox > .isso-form-wrapper > .isso-auth-section .isso-post-action {
margin-top: 0;
}
}
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | Oops, that happened because I squashed the commit where I removed the explicit color styling into that one and didn't rename it. I updated it now | BBaoVanC | 44 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/js/app/config.js | var utils = require("app/utils");
"use strict";
var config = {
"css": true,
"css-url": null,
"lang": "",
"default-lang": "en",
"reply-to-self": false,
"require-email": false,
"require-author": false,
"reply-notifications": false,
"reply-notifications-default-enabled": false,
"max-comments-top": "inf",
"max-comments-nested": 5,
"reveal-on-click": 5,
"gravatar": false,
"avatar": true,
"avatar-bg": "#f0f0f0",
"avatar-fg": ["#9abf88", "#5698c4", "#e279a3", "#9163b6",
"#be5168", "#f19670", "#e4bf80", "#447c69"].join(" "),
"vote": true,
"vote-levels": null,
"feed": false
};
var js = document.getElementsByTagName("script");
for (var i = 0; i < js.length; i++) {
for (var j = 0; j < js[i].attributes.length; j++) {
var attr = js[i].attributes[j];
if (/^data-isso-/.test(attr.name)) {
try {
config[attr.name.substring(10)] = JSON.parse(attr.value);
} catch (ex) {
config[attr.name.substring(10)] = attr.value;
}
}
}
}
// split avatar-fg on whitespace
config["avatar-fg"] = config["avatar-fg"].split(" ");
// create an array of normalized language codes from:
// - config["lang"], if it is nonempty
// - the first of navigator.languages, navigator.language, and
// navigator.userLanguage that exists and has a nonempty value
// - config["default-lang"]
// - "en" as an ultimate fallback
// i18n.js will use the first code in this array for which we have
// a translation.
var languages = [];
var found_navlang = false;
if (config["lang"]) {
languages.push(utils.normalize_bcp47(config["lang"]));
}
if (navigator.languages) {
for (i = 0; i < navigator.languages.length; i++) {
if (navigator.languages[i]) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.languages[i]));
}
}
}
if (!found_navlang && navigator.language) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.language));
}
if (!found_navlang && navigator.userLanguage) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.userLanguage));
}
if (config["default-lang"]) {
languages.push(utils.normalize_bcp47(config["default-lang"]));
}
languages.push("en");
config["langs"] = languages;
// code outside this file should look only at langs
delete config["lang"];
delete config["default-lang"];
module.exports = config;
| var utils = require("app/utils");
"use strict";
var config = {
"css": true,
"css-url": null,
"lang": "",
"default-lang": "en",
"reply-to-self": false,
"require-email": false,
"require-author": false,
"reply-notifications": false,
"reply-notifications-default-enabled": false,
"max-comments-top": "inf",
"max-comments-nested": 5,
"reveal-on-click": 5,
"gravatar": false,
"avatar": true,
"avatar-bg": "#f0f0f0",
"avatar-fg": ["#9abf88", "#5698c4", "#e279a3", "#9163b6",
"#be5168", "#f19670", "#e4bf80", "#447c69"].join(" "),
"vote": true,
"vote-levels": null,
"feed": false,
"page-author-hashes": "",
};
var js = document.getElementsByTagName("script");
for (var i = 0; i < js.length; i++) {
for (var j = 0; j < js[i].attributes.length; j++) {
var attr = js[i].attributes[j];
if (/^data-isso-/.test(attr.name)) {
try {
config[attr.name.substring(10)] = JSON.parse(attr.value);
} catch (ex) {
config[attr.name.substring(10)] = attr.value;
}
}
}
}
// split avatar-fg on whitespace
config["avatar-fg"] = config["avatar-fg"].split(" ");
// create an array of normalized language codes from:
// - config["lang"], if it is nonempty
// - the first of navigator.languages, navigator.language, and
// navigator.userLanguage that exists and has a nonempty value
// - config["default-lang"]
// - "en" as an ultimate fallback
// i18n.js will use the first code in this array for which we have
// a translation.
var languages = [];
var found_navlang = false;
if (config["lang"]) {
languages.push(utils.normalize_bcp47(config["lang"]));
}
if (navigator.languages) {
for (i = 0; i < navigator.languages.length; i++) {
if (navigator.languages[i]) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.languages[i]));
}
}
}
if (!found_navlang && navigator.language) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.language));
}
if (!found_navlang && navigator.userLanguage) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.userLanguage));
}
if (config["default-lang"]) {
languages.push(utils.normalize_bcp47(config["default-lang"]));
}
languages.push("en");
config["langs"] = languages;
// code outside this file should look only at langs
delete config["lang"];
delete config["default-lang"];
// Convert page-author-hash into a array by splitting at whitespace and/or commas
config["page-author-hashes"] = config["page-author-hashes"].split(/[\s,]+/);
module.exports = config;
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | Please comment in the code what this does, it's not very obvious to JS beginners at first glance
`// Split "page-author-hash" by comma and spaces into array` | ix5 | 45 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/js/app/isso.js | /* Isso – Ich schrei sonst!
*/
var $ = require("app/dom");
var utils = require("app/utils");
var config = require("app/config");
var api = require("app/api");
var template = require("app/template");
var i18n = require("app/i18n");
var identicons = require("app/lib/identicons");
var globals = require("app/globals");
"use strict";
var editorify = function(el) {
el = $.htmlify(el);
el.setAttribute("contentEditable", true);
el.on("focus", function() {
if (el.classList.contains("isso-placeholder")) {
el.innerHTML = "";
el.classList.remove("isso-placeholder");
}
});
el.on("blur", function() {
if (el.textContent.length === 0) {
el.textContent = i18n.translate("postbox-text");
el.classList.add("isso-placeholder");
}
});
return el;
}
var Postbox = function(parent) {
var localStorage = utils.localStorageImpl,
el = $.htmlify(template.render("postbox", {
"author": JSON.parse(localStorage.getItem("isso-author")),
"email": JSON.parse(localStorage.getItem("isso-email")),
"website": JSON.parse(localStorage.getItem("isso-website")),
"preview": ''
}));
// callback on success (e.g. to toggle the reply button)
el.onsuccess = function() {};
el.validate = function() {
if (utils.text($(".isso-textarea", this).innerHTML).length < 3 ||
$(".isso-textarea", this).classList.contains("isso-placeholder"))
{
$(".isso-textarea", this).focus();
return false;
}
if (config["require-email"] &&
$("[name='email']", this).value.length <= 0)
{
$("[name='email']", this).focus();
return false;
}
if (config["require-author"] &&
$("[name='author']", this).value.length <= 0)
{
$("[name='author']", this).focus();
return false;
}
return true;
};
// only display notification checkbox if email is filled in
var email_edit = function() {
if (config["reply-notifications"] && $("[name='email']", el).value.length > 0) {
$(".isso-notification-section", el).show();
} else {
$(".isso-notification-section", el).hide();
}
};
$("[name='email']", el).on("input", email_edit);
email_edit();
// email is not optional if this config parameter is set
if (config["require-email"]) {
$("[for='isso-postbox-email']", el).textContent =
$("[for='isso-postbox-email']", el).textContent.replace(/ \(.*\)/, "");
}
// author is not optional if this config parameter is set
if (config["require-author"]) {
$("[for='isso-postbox-author']", el).textContent =
$("[for='isso-postbox-author']", el).textContent.replace(/ \(.*\)/, "");
}
// preview function
$("[name='preview']", el).on("click", function() {
api.preview(utils.text($(".isso-textarea", el).innerHTML)).then(
function(html) {
$(".isso-preview .isso-text", el).innerHTML = html;
el.classList.add('isso-preview-mode');
});
});
// edit function
var edit = function() {
$(".isso-preview .isso-text", el).innerHTML = '';
el.classList.remove('isso-preview-mode');
};
$("[name='edit']", el).on("click", edit);
$(".isso-preview", el).on("click", edit);
// submit form, initialize optional fields with `null` and reset form.
// If replied to a comment, remove form completely.
$("[type=submit]", el).on("click", function() {
edit();
if (! el.validate()) {
return;
}
var author = $("[name=author]", el).value || null,
email = $("[name=email]", el).value || null,
website = $("[name=website]", el).value || null;
localStorage.setItem("isso-author", JSON.stringify(author));
localStorage.setItem("isso-email", JSON.stringify(email));
localStorage.setItem("isso-website", JSON.stringify(website));
api.create($("#isso-thread").getAttribute("data-isso-id"), {
author: author, email: email, website: website,
text: utils.text($(".isso-textarea", el).innerHTML),
parent: parent || null,
title: $("#isso-thread").getAttribute("data-title") || null,
notification: $("[name=notification]", el).checked() ? 1 : 0,
}).then(function(comment) {
$(".isso-textarea", el).innerHTML = "";
$(".isso-textarea", el).blur();
insert(comment, true);
if (parent !== null) {
el.onsuccess();
}
});
});
editorify($(".isso-textarea", el));
return el;
};
var insert_loader = function(comment, lastcreated) {
var entrypoint;
if (comment.id === null) {
entrypoint = $("#isso-root");
comment.name = 'null';
} else {
entrypoint = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-follow-up");
comment.name = comment.id;
}
var el = $.htmlify(template.render("comment-loader", {"comment": comment}));
entrypoint.append(el);
$("a.isso-load-hidden", el).on("click", function() {
el.remove();
api.fetch($("#isso-thread").getAttribute("data-isso-id"),
config["reveal-on-click"], config["max-comments-nested"],
comment.id,
lastcreated).then(
function(rv) {
if (rv.total_replies === 0) {
return;
}
var lastcreated = 0;
rv.replies.forEach(function(commentObject) {
insert(commentObject, false);
if(commentObject.created > lastcreated) {
lastcreated = commentObject.created;
}
});
if(rv.hidden_replies > 0) {
insert_loader(rv, lastcreated);
}
},
function(err) {
console.log(err);
});
});
};
var insert = function(comment, scrollIntoView) {
var el = $.htmlify(template.render("comment", {"comment": comment}));
// update datetime every 60 seconds
var refresh = function() {
$(".isso-permalink > time", el).textContent = i18n.ago(
globals.offset.localTime(), new Date(parseInt(comment.created, 10) * 1000));
setTimeout(refresh, 60*1000);
};
// run once to activate
refresh();
if (config["avatar"]) {
$(".isso-avatar > svg", el).replace(identicons.generate(comment.hash, 4, 48, config));
}
var entrypoint;
if (comment.parent === null) {
entrypoint = $("#isso-root");
} else {
entrypoint = $("#isso-" + comment.parent + " > .isso-text-wrapper > .isso-follow-up");
}
entrypoint.append(el);
if (scrollIntoView) {
el.scrollIntoView();
}
var footer = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-footer"),
header = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-header"),
text = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-text");
var form = null; // XXX: probably a good place for a closure
$("a.isso-reply", footer).toggle("click",
function(toggler) {
form = footer.insertAfter(new Postbox(comment.parent === null ? comment.id : comment.parent));
form.onsuccess = function() { toggler.next(); };
$(".isso-textarea", form).focus();
$("a.isso-reply", footer).textContent = i18n.translate("comment-close");
},
function() {
form.remove();
$("a.isso-reply", footer).textContent = i18n.translate("comment-reply");
}
);
if (config.vote) {
var voteLevels = config['vote-levels'];
if (typeof voteLevels === 'string') {
// Eg. -5,5,15
voteLevels = voteLevels.split(',');
}
// update vote counter
var votes = function (value) {
var span = $("span.isso-votes", footer);
if (span === null) {
footer.prepend($.new("span.isso-votes", value));
} else {
span.textContent = value;
}
if (value) {
el.classList.remove('isso-no-votes');
} else {
el.classList.add('isso-no-votes');
}
if (voteLevels) {
var before = true;
for (var index = 0; index <= voteLevels.length; index++) {
if (before && (index >= voteLevels.length || value < voteLevels[index])) {
el.classList.add('isso-vote-level-' + index);
before = false;
} else {
el.classList.remove('isso-vote-level-' + index);
}
}
}
};
$("a.isso-upvote", footer).on("click", function () {
api.like(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
$("a.isso-downvote", footer).on("click", function () {
api.dislike(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
votes(comment.likes - comment.dislikes);
}
$("a.isso-edit", footer).toggle("click",
function(toggler) {
var edit = $("a.isso-edit", footer);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
edit.textContent = i18n.translate("comment-save");
edit.insertAfter($.new("a.isso-cancel", i18n.translate("comment-cancel"))).on("click", function() {
toggler.canceled = true;
toggler.next();
});
toggler.canceled = false;
api.view(comment.id, 1).then(function(rv) {
var textarea = editorify($.new("div.isso-textarea"));
textarea.innerHTML = utils.detext(rv.text);
textarea.focus();
text.classList.remove("isso-text");
text.classList.add("isso-textarea-wrapper");
text.textContent = "";
text.append(textarea);
});
if (avatar !== null) {
avatar.hide();
}
},
function(toggler) {
var textarea = $(".isso-textarea", text);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
if (! toggler.canceled && textarea !== null) {
if (utils.text(textarea.innerHTML).length < 3) {
textarea.focus();
toggler.wait();
return;
} else {
api.modify(comment.id, {"text": utils.text(textarea.innerHTML)}).then(function(rv) {
text.innerHTML = rv.text;
comment.text = rv.text;
});
}
} else {
text.innerHTML = comment.text;
}
text.classList.remove("isso-textarea-wrapper");
text.classList.add("isso-text");
if (avatar !== null) {
avatar.show();
}
$("a.isso-cancel", footer).remove();
$("a.isso-edit", footer).textContent = i18n.translate("comment-edit");
}
);
$("a.isso-delete", footer).toggle("click",
function(toggler) {
var del = $("a.isso-delete", footer);
var state = ! toggler.state;
del.textContent = i18n.translate("comment-confirm");
del.on("mouseout", function() {
del.textContent = i18n.translate("comment-delete");
toggler.state = state;
del.onmouseout = null;
});
},
function() {
var del = $("a.isso-delete", footer);
api.remove(comment.id).then(function(rv) {
if (rv) {
el.remove();
} else {
$("span.isso-note", header).textContent = i18n.translate("comment-deleted");
text.innerHTML = "<p> </p>";
$("a.isso-edit", footer).remove();
$("a.isso-delete", footer).remove();
}
del.textContent = i18n.translate("comment-delete");
});
}
);
// remove edit and delete buttons when cookie is gone
var clear = function(button) {
if (! utils.cookie("isso-" + comment.id)) {
if ($(button, footer) !== null) {
$(button, footer).remove();
}
} else {
setTimeout(function() { clear(button); }, 15*1000);
}
};
clear("a.isso-edit");
clear("a.isso-delete");
// show direct reply to own comment when cookie is max aged
var show = function(el) {
if (utils.cookie("isso-" + comment.id)) {
setTimeout(function() { show(el); }, 15*1000);
} else {
footer.append(el);
}
};
if (! config["reply-to-self"] && utils.cookie("isso-" + comment.id)) {
show($("a.isso-reply", footer).detach());
}
if(comment.hasOwnProperty('replies')) {
var lastcreated = 0;
comment.replies.forEach(function(replyObject) {
insert(replyObject, false);
if(replyObject.created > lastcreated) {
lastcreated = replyObject.created;
}
});
if(comment.hidden_replies > 0) {
insert_loader(comment, lastcreated);
}
}
};
module.exports = {
insert: insert,
insert_loader: insert_loader,
Postbox: Postbox,
};
| /* Isso – Ich schrei sonst!
*/
var $ = require("app/dom");
var utils = require("app/utils");
var config = require("app/config");
var api = require("app/api");
var template = require("app/template");
var i18n = require("app/i18n");
var identicons = require("app/lib/identicons");
var globals = require("app/globals");
"use strict";
var editorify = function(el) {
el = $.htmlify(el);
el.setAttribute("contentEditable", true);
el.on("focus", function() {
if (el.classList.contains("isso-placeholder")) {
el.innerHTML = "";
el.classList.remove("isso-placeholder");
}
});
el.on("blur", function() {
if (el.textContent.length === 0) {
el.textContent = i18n.translate("postbox-text");
el.classList.add("isso-placeholder");
}
});
return el;
}
var Postbox = function(parent) {
var localStorage = utils.localStorageImpl,
el = $.htmlify(template.render("postbox", {
"author": JSON.parse(localStorage.getItem("isso-author")),
"email": JSON.parse(localStorage.getItem("isso-email")),
"website": JSON.parse(localStorage.getItem("isso-website")),
"preview": ''
}));
// callback on success (e.g. to toggle the reply button)
el.onsuccess = function() {};
el.validate = function() {
if (utils.text($(".isso-textarea", this).innerHTML).length < 3 ||
$(".isso-textarea", this).classList.contains("isso-placeholder"))
{
$(".isso-textarea", this).focus();
return false;
}
if (config["require-email"] &&
$("[name='email']", this).value.length <= 0)
{
$("[name='email']", this).focus();
return false;
}
if (config["require-author"] &&
$("[name='author']", this).value.length <= 0)
{
$("[name='author']", this).focus();
return false;
}
return true;
};
// only display notification checkbox if email is filled in
var email_edit = function() {
if (config["reply-notifications"] && $("[name='email']", el).value.length > 0) {
$(".isso-notification-section", el).show();
} else {
$(".isso-notification-section", el).hide();
}
};
$("[name='email']", el).on("input", email_edit);
email_edit();
// email is not optional if this config parameter is set
if (config["require-email"]) {
$("[for='isso-postbox-email']", el).textContent =
$("[for='isso-postbox-email']", el).textContent.replace(/ \(.*\)/, "");
}
// author is not optional if this config parameter is set
if (config["require-author"]) {
$("[for='isso-postbox-author']", el).textContent =
$("[for='isso-postbox-author']", el).textContent.replace(/ \(.*\)/, "");
}
// preview function
$("[name='preview']", el).on("click", function() {
api.preview(utils.text($(".isso-textarea", el).innerHTML)).then(
function(html) {
$(".isso-preview .isso-text", el).innerHTML = html;
el.classList.add('isso-preview-mode');
});
});
// edit function
var edit = function() {
$(".isso-preview .isso-text", el).innerHTML = '';
el.classList.remove('isso-preview-mode');
};
$("[name='edit']", el).on("click", edit);
$(".isso-preview", el).on("click", edit);
// submit form, initialize optional fields with `null` and reset form.
// If replied to a comment, remove form completely.
$("[type=submit]", el).on("click", function() {
edit();
if (! el.validate()) {
return;
}
var author = $("[name=author]", el).value || null,
email = $("[name=email]", el).value || null,
website = $("[name=website]", el).value || null;
localStorage.setItem("isso-author", JSON.stringify(author));
localStorage.setItem("isso-email", JSON.stringify(email));
localStorage.setItem("isso-website", JSON.stringify(website));
api.create($("#isso-thread").getAttribute("data-isso-id"), {
author: author, email: email, website: website,
text: utils.text($(".isso-textarea", el).innerHTML),
parent: parent || null,
title: $("#isso-thread").getAttribute("data-title") || null,
notification: $("[name=notification]", el).checked() ? 1 : 0,
}).then(function(comment) {
$(".isso-textarea", el).innerHTML = "";
$(".isso-textarea", el).blur();
insert(comment, true);
if (parent !== null) {
el.onsuccess();
}
});
});
editorify($(".isso-textarea", el));
return el;
};
var insert_loader = function(comment, lastcreated) {
var entrypoint;
if (comment.id === null) {
entrypoint = $("#isso-root");
comment.name = 'null';
} else {
entrypoint = $("#isso-" + comment.id + " > .isso-follow-up");
comment.name = comment.id;
}
var el = $.htmlify(template.render("comment-loader", {"comment": comment}));
entrypoint.append(el);
$("a.isso-load-hidden", el).on("click", function() {
el.remove();
api.fetch($("#isso-thread").getAttribute("data-isso-id"),
config["reveal-on-click"], config["max-comments-nested"],
comment.id,
lastcreated).then(
function(rv) {
if (rv.total_replies === 0) {
return;
}
var lastcreated = 0;
rv.replies.forEach(function(commentObject) {
insert(commentObject, false);
if(commentObject.created > lastcreated) {
lastcreated = commentObject.created;
}
});
if(rv.hidden_replies > 0) {
insert_loader(rv, lastcreated);
}
},
function(err) {
console.log(err);
});
});
};
var insert = function(comment, scrollIntoView) {
var el = $.htmlify(template.render("comment", {"comment": comment}));
// update datetime every 60 seconds
var refresh = function() {
$(".isso-permalink > time", el).textContent = i18n.ago(
globals.offset.localTime(), new Date(parseInt(comment.created, 10) * 1000));
setTimeout(refresh, 60*1000);
};
// run once to activate
refresh();
if (config["avatar"]) {
$(".isso-avatar > svg", el).replace(identicons.generate(comment.hash, 4, 48, config));
}
var entrypoint;
if (comment.parent === null) {
entrypoint = $("#isso-root");
} else {
entrypoint = $("#isso-" + comment.parent + " > .isso-follow-up");
}
entrypoint.append(el);
if (scrollIntoView) {
el.scrollIntoView();
}
var footer = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-footer"),
header = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-header"),
text = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-text");
var form = null; // XXX: probably a good place for a closure
$("a.isso-reply", footer).toggle("click",
function(toggler) {
form = footer.insertAfter(new Postbox(comment.parent === null ? comment.id : comment.parent));
form.onsuccess = function() { toggler.next(); };
$(".isso-textarea", form).focus();
$("a.isso-reply", footer).textContent = i18n.translate("comment-close");
},
function() {
form.remove();
$("a.isso-reply", footer).textContent = i18n.translate("comment-reply");
}
);
if (config.vote) {
var voteLevels = config['vote-levels'];
if (typeof voteLevels === 'string') {
// Eg. -5,5,15
voteLevels = voteLevels.split(',');
}
// update vote counter
var votes = function (value) {
var span = $("span.isso-votes", footer);
if (span === null) {
footer.prepend($.new("span.isso-votes", value));
} else {
span.textContent = value;
}
if (value) {
el.classList.remove('isso-no-votes');
} else {
el.classList.add('isso-no-votes');
}
if (voteLevels) {
var before = true;
for (var index = 0; index <= voteLevels.length; index++) {
if (before && (index >= voteLevels.length || value < voteLevels[index])) {
el.classList.add('isso-vote-level-' + index);
before = false;
} else {
el.classList.remove('isso-vote-level-' + index);
}
}
}
};
$("a.isso-upvote", footer).on("click", function () {
api.like(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
$("a.isso-downvote", footer).on("click", function () {
api.dislike(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
votes(comment.likes - comment.dislikes);
}
$("a.isso-edit", footer).toggle("click",
function(toggler) {
var edit = $("a.isso-edit", footer);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
edit.textContent = i18n.translate("comment-save");
edit.insertAfter($.new("a.isso-cancel", i18n.translate("comment-cancel"))).on("click", function() {
toggler.canceled = true;
toggler.next();
});
toggler.canceled = false;
api.view(comment.id, 1).then(function(rv) {
var textarea = editorify($.new("div.isso-textarea"));
textarea.innerHTML = utils.detext(rv.text);
textarea.focus();
text.classList.remove("isso-text");
text.classList.add("isso-textarea-wrapper");
text.textContent = "";
text.append(textarea);
});
if (avatar !== null) {
avatar.hide();
}
},
function(toggler) {
var textarea = $(".isso-textarea", text);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
if (! toggler.canceled && textarea !== null) {
if (utils.text(textarea.innerHTML).length < 3) {
textarea.focus();
toggler.wait();
return;
} else {
api.modify(comment.id, {"text": utils.text(textarea.innerHTML)}).then(function(rv) {
text.innerHTML = rv.text;
comment.text = rv.text;
});
}
} else {
text.innerHTML = comment.text;
}
text.classList.remove("isso-textarea-wrapper");
text.classList.add("isso-text");
if (avatar !== null) {
avatar.show();
}
$("a.isso-cancel", footer).remove();
$("a.isso-edit", footer).textContent = i18n.translate("comment-edit");
}
);
$("a.isso-delete", footer).toggle("click",
function(toggler) {
var del = $("a.isso-delete", footer);
var state = ! toggler.state;
del.textContent = i18n.translate("comment-confirm");
del.on("mouseout", function() {
del.textContent = i18n.translate("comment-delete");
toggler.state = state;
del.onmouseout = null;
});
},
function() {
var del = $("a.isso-delete", footer);
api.remove(comment.id).then(function(rv) {
if (rv) {
el.remove();
} else {
$("span.isso-note", header).textContent = i18n.translate("comment-deleted");
text.innerHTML = "<p> </p>";
$("a.isso-edit", footer).remove();
$("a.isso-delete", footer).remove();
}
del.textContent = i18n.translate("comment-delete");
});
}
);
// remove edit and delete buttons when cookie is gone
var clear = function(button) {
if (! utils.cookie("isso-" + comment.id)) {
if ($(button, footer) !== null) {
$(button, footer).remove();
}
} else {
setTimeout(function() { clear(button); }, 15*1000);
}
};
clear("a.isso-edit");
clear("a.isso-delete");
// show direct reply to own comment when cookie is max aged
var show = function(el) {
if (utils.cookie("isso-" + comment.id)) {
setTimeout(function() { show(el); }, 15*1000);
} else {
footer.append(el);
}
};
if (! config["reply-to-self"] && utils.cookie("isso-" + comment.id)) {
show($("a.isso-reply", footer).detach());
}
if(comment.hasOwnProperty('replies')) {
var lastcreated = 0;
comment.replies.forEach(function(replyObject) {
insert(replyObject, false);
if(replyObject.created > lastcreated) {
lastcreated = replyObject.created;
}
});
if(comment.hidden_replies > 0) {
insert_loader(comment, lastcreated);
}
}
};
module.exports = {
insert: insert,
insert_loader: insert_loader,
Postbox: Postbox,
};
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | You might want to write a test case for this - template code and `isso.js` relying on DOM selectors such as `$('#isso-x')` has caused trouble before, e.g. https://github.com/posativ/isso/issues/524
See https://isso-comments.github.io/docs/technical-docs/testing-client/ (latest docs not uploaded to posativ.org yet) and `isso/js/tests/unit/` for examples. | ix5 | 46 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/js/app/isso.js | /* Isso – Ich schrei sonst!
*/
var $ = require("app/dom");
var utils = require("app/utils");
var config = require("app/config");
var api = require("app/api");
var template = require("app/template");
var i18n = require("app/i18n");
var identicons = require("app/lib/identicons");
var globals = require("app/globals");
"use strict";
var editorify = function(el) {
el = $.htmlify(el);
el.setAttribute("contentEditable", true);
el.on("focus", function() {
if (el.classList.contains("isso-placeholder")) {
el.innerHTML = "";
el.classList.remove("isso-placeholder");
}
});
el.on("blur", function() {
if (el.textContent.length === 0) {
el.textContent = i18n.translate("postbox-text");
el.classList.add("isso-placeholder");
}
});
return el;
}
var Postbox = function(parent) {
var localStorage = utils.localStorageImpl,
el = $.htmlify(template.render("postbox", {
"author": JSON.parse(localStorage.getItem("isso-author")),
"email": JSON.parse(localStorage.getItem("isso-email")),
"website": JSON.parse(localStorage.getItem("isso-website")),
"preview": ''
}));
// callback on success (e.g. to toggle the reply button)
el.onsuccess = function() {};
el.validate = function() {
if (utils.text($(".isso-textarea", this).innerHTML).length < 3 ||
$(".isso-textarea", this).classList.contains("isso-placeholder"))
{
$(".isso-textarea", this).focus();
return false;
}
if (config["require-email"] &&
$("[name='email']", this).value.length <= 0)
{
$("[name='email']", this).focus();
return false;
}
if (config["require-author"] &&
$("[name='author']", this).value.length <= 0)
{
$("[name='author']", this).focus();
return false;
}
return true;
};
// only display notification checkbox if email is filled in
var email_edit = function() {
if (config["reply-notifications"] && $("[name='email']", el).value.length > 0) {
$(".isso-notification-section", el).show();
} else {
$(".isso-notification-section", el).hide();
}
};
$("[name='email']", el).on("input", email_edit);
email_edit();
// email is not optional if this config parameter is set
if (config["require-email"]) {
$("[for='isso-postbox-email']", el).textContent =
$("[for='isso-postbox-email']", el).textContent.replace(/ \(.*\)/, "");
}
// author is not optional if this config parameter is set
if (config["require-author"]) {
$("[for='isso-postbox-author']", el).textContent =
$("[for='isso-postbox-author']", el).textContent.replace(/ \(.*\)/, "");
}
// preview function
$("[name='preview']", el).on("click", function() {
api.preview(utils.text($(".isso-textarea", el).innerHTML)).then(
function(html) {
$(".isso-preview .isso-text", el).innerHTML = html;
el.classList.add('isso-preview-mode');
});
});
// edit function
var edit = function() {
$(".isso-preview .isso-text", el).innerHTML = '';
el.classList.remove('isso-preview-mode');
};
$("[name='edit']", el).on("click", edit);
$(".isso-preview", el).on("click", edit);
// submit form, initialize optional fields with `null` and reset form.
// If replied to a comment, remove form completely.
$("[type=submit]", el).on("click", function() {
edit();
if (! el.validate()) {
return;
}
var author = $("[name=author]", el).value || null,
email = $("[name=email]", el).value || null,
website = $("[name=website]", el).value || null;
localStorage.setItem("isso-author", JSON.stringify(author));
localStorage.setItem("isso-email", JSON.stringify(email));
localStorage.setItem("isso-website", JSON.stringify(website));
api.create($("#isso-thread").getAttribute("data-isso-id"), {
author: author, email: email, website: website,
text: utils.text($(".isso-textarea", el).innerHTML),
parent: parent || null,
title: $("#isso-thread").getAttribute("data-title") || null,
notification: $("[name=notification]", el).checked() ? 1 : 0,
}).then(function(comment) {
$(".isso-textarea", el).innerHTML = "";
$(".isso-textarea", el).blur();
insert(comment, true);
if (parent !== null) {
el.onsuccess();
}
});
});
editorify($(".isso-textarea", el));
return el;
};
var insert_loader = function(comment, lastcreated) {
var entrypoint;
if (comment.id === null) {
entrypoint = $("#isso-root");
comment.name = 'null';
} else {
entrypoint = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-follow-up");
comment.name = comment.id;
}
var el = $.htmlify(template.render("comment-loader", {"comment": comment}));
entrypoint.append(el);
$("a.isso-load-hidden", el).on("click", function() {
el.remove();
api.fetch($("#isso-thread").getAttribute("data-isso-id"),
config["reveal-on-click"], config["max-comments-nested"],
comment.id,
lastcreated).then(
function(rv) {
if (rv.total_replies === 0) {
return;
}
var lastcreated = 0;
rv.replies.forEach(function(commentObject) {
insert(commentObject, false);
if(commentObject.created > lastcreated) {
lastcreated = commentObject.created;
}
});
if(rv.hidden_replies > 0) {
insert_loader(rv, lastcreated);
}
},
function(err) {
console.log(err);
});
});
};
var insert = function(comment, scrollIntoView) {
var el = $.htmlify(template.render("comment", {"comment": comment}));
// update datetime every 60 seconds
var refresh = function() {
$(".isso-permalink > time", el).textContent = i18n.ago(
globals.offset.localTime(), new Date(parseInt(comment.created, 10) * 1000));
setTimeout(refresh, 60*1000);
};
// run once to activate
refresh();
if (config["avatar"]) {
$(".isso-avatar > svg", el).replace(identicons.generate(comment.hash, 4, 48, config));
}
var entrypoint;
if (comment.parent === null) {
entrypoint = $("#isso-root");
} else {
entrypoint = $("#isso-" + comment.parent + " > .isso-text-wrapper > .isso-follow-up");
}
entrypoint.append(el);
if (scrollIntoView) {
el.scrollIntoView();
}
var footer = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-footer"),
header = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-header"),
text = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-text");
var form = null; // XXX: probably a good place for a closure
$("a.isso-reply", footer).toggle("click",
function(toggler) {
form = footer.insertAfter(new Postbox(comment.parent === null ? comment.id : comment.parent));
form.onsuccess = function() { toggler.next(); };
$(".isso-textarea", form).focus();
$("a.isso-reply", footer).textContent = i18n.translate("comment-close");
},
function() {
form.remove();
$("a.isso-reply", footer).textContent = i18n.translate("comment-reply");
}
);
if (config.vote) {
var voteLevels = config['vote-levels'];
if (typeof voteLevels === 'string') {
// Eg. -5,5,15
voteLevels = voteLevels.split(',');
}
// update vote counter
var votes = function (value) {
var span = $("span.isso-votes", footer);
if (span === null) {
footer.prepend($.new("span.isso-votes", value));
} else {
span.textContent = value;
}
if (value) {
el.classList.remove('isso-no-votes');
} else {
el.classList.add('isso-no-votes');
}
if (voteLevels) {
var before = true;
for (var index = 0; index <= voteLevels.length; index++) {
if (before && (index >= voteLevels.length || value < voteLevels[index])) {
el.classList.add('isso-vote-level-' + index);
before = false;
} else {
el.classList.remove('isso-vote-level-' + index);
}
}
}
};
$("a.isso-upvote", footer).on("click", function () {
api.like(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
$("a.isso-downvote", footer).on("click", function () {
api.dislike(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
votes(comment.likes - comment.dislikes);
}
$("a.isso-edit", footer).toggle("click",
function(toggler) {
var edit = $("a.isso-edit", footer);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
edit.textContent = i18n.translate("comment-save");
edit.insertAfter($.new("a.isso-cancel", i18n.translate("comment-cancel"))).on("click", function() {
toggler.canceled = true;
toggler.next();
});
toggler.canceled = false;
api.view(comment.id, 1).then(function(rv) {
var textarea = editorify($.new("div.isso-textarea"));
textarea.innerHTML = utils.detext(rv.text);
textarea.focus();
text.classList.remove("isso-text");
text.classList.add("isso-textarea-wrapper");
text.textContent = "";
text.append(textarea);
});
if (avatar !== null) {
avatar.hide();
}
},
function(toggler) {
var textarea = $(".isso-textarea", text);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
if (! toggler.canceled && textarea !== null) {
if (utils.text(textarea.innerHTML).length < 3) {
textarea.focus();
toggler.wait();
return;
} else {
api.modify(comment.id, {"text": utils.text(textarea.innerHTML)}).then(function(rv) {
text.innerHTML = rv.text;
comment.text = rv.text;
});
}
} else {
text.innerHTML = comment.text;
}
text.classList.remove("isso-textarea-wrapper");
text.classList.add("isso-text");
if (avatar !== null) {
avatar.show();
}
$("a.isso-cancel", footer).remove();
$("a.isso-edit", footer).textContent = i18n.translate("comment-edit");
}
);
$("a.isso-delete", footer).toggle("click",
function(toggler) {
var del = $("a.isso-delete", footer);
var state = ! toggler.state;
del.textContent = i18n.translate("comment-confirm");
del.on("mouseout", function() {
del.textContent = i18n.translate("comment-delete");
toggler.state = state;
del.onmouseout = null;
});
},
function() {
var del = $("a.isso-delete", footer);
api.remove(comment.id).then(function(rv) {
if (rv) {
el.remove();
} else {
$("span.isso-note", header).textContent = i18n.translate("comment-deleted");
text.innerHTML = "<p> </p>";
$("a.isso-edit", footer).remove();
$("a.isso-delete", footer).remove();
}
del.textContent = i18n.translate("comment-delete");
});
}
);
// remove edit and delete buttons when cookie is gone
var clear = function(button) {
if (! utils.cookie("isso-" + comment.id)) {
if ($(button, footer) !== null) {
$(button, footer).remove();
}
} else {
setTimeout(function() { clear(button); }, 15*1000);
}
};
clear("a.isso-edit");
clear("a.isso-delete");
// show direct reply to own comment when cookie is max aged
var show = function(el) {
if (utils.cookie("isso-" + comment.id)) {
setTimeout(function() { show(el); }, 15*1000);
} else {
footer.append(el);
}
};
if (! config["reply-to-self"] && utils.cookie("isso-" + comment.id)) {
show($("a.isso-reply", footer).detach());
}
if(comment.hasOwnProperty('replies')) {
var lastcreated = 0;
comment.replies.forEach(function(replyObject) {
insert(replyObject, false);
if(replyObject.created > lastcreated) {
lastcreated = replyObject.created;
}
});
if(comment.hidden_replies > 0) {
insert_loader(comment, lastcreated);
}
}
};
module.exports = {
insert: insert,
insert_loader: insert_loader,
Postbox: Postbox,
};
| /* Isso – Ich schrei sonst!
*/
var $ = require("app/dom");
var utils = require("app/utils");
var config = require("app/config");
var api = require("app/api");
var template = require("app/template");
var i18n = require("app/i18n");
var identicons = require("app/lib/identicons");
var globals = require("app/globals");
"use strict";
var editorify = function(el) {
el = $.htmlify(el);
el.setAttribute("contentEditable", true);
el.on("focus", function() {
if (el.classList.contains("isso-placeholder")) {
el.innerHTML = "";
el.classList.remove("isso-placeholder");
}
});
el.on("blur", function() {
if (el.textContent.length === 0) {
el.textContent = i18n.translate("postbox-text");
el.classList.add("isso-placeholder");
}
});
return el;
}
var Postbox = function(parent) {
var localStorage = utils.localStorageImpl,
el = $.htmlify(template.render("postbox", {
"author": JSON.parse(localStorage.getItem("isso-author")),
"email": JSON.parse(localStorage.getItem("isso-email")),
"website": JSON.parse(localStorage.getItem("isso-website")),
"preview": ''
}));
// callback on success (e.g. to toggle the reply button)
el.onsuccess = function() {};
el.validate = function() {
if (utils.text($(".isso-textarea", this).innerHTML).length < 3 ||
$(".isso-textarea", this).classList.contains("isso-placeholder"))
{
$(".isso-textarea", this).focus();
return false;
}
if (config["require-email"] &&
$("[name='email']", this).value.length <= 0)
{
$("[name='email']", this).focus();
return false;
}
if (config["require-author"] &&
$("[name='author']", this).value.length <= 0)
{
$("[name='author']", this).focus();
return false;
}
return true;
};
// only display notification checkbox if email is filled in
var email_edit = function() {
if (config["reply-notifications"] && $("[name='email']", el).value.length > 0) {
$(".isso-notification-section", el).show();
} else {
$(".isso-notification-section", el).hide();
}
};
$("[name='email']", el).on("input", email_edit);
email_edit();
// email is not optional if this config parameter is set
if (config["require-email"]) {
$("[for='isso-postbox-email']", el).textContent =
$("[for='isso-postbox-email']", el).textContent.replace(/ \(.*\)/, "");
}
// author is not optional if this config parameter is set
if (config["require-author"]) {
$("[for='isso-postbox-author']", el).textContent =
$("[for='isso-postbox-author']", el).textContent.replace(/ \(.*\)/, "");
}
// preview function
$("[name='preview']", el).on("click", function() {
api.preview(utils.text($(".isso-textarea", el).innerHTML)).then(
function(html) {
$(".isso-preview .isso-text", el).innerHTML = html;
el.classList.add('isso-preview-mode');
});
});
// edit function
var edit = function() {
$(".isso-preview .isso-text", el).innerHTML = '';
el.classList.remove('isso-preview-mode');
};
$("[name='edit']", el).on("click", edit);
$(".isso-preview", el).on("click", edit);
// submit form, initialize optional fields with `null` and reset form.
// If replied to a comment, remove form completely.
$("[type=submit]", el).on("click", function() {
edit();
if (! el.validate()) {
return;
}
var author = $("[name=author]", el).value || null,
email = $("[name=email]", el).value || null,
website = $("[name=website]", el).value || null;
localStorage.setItem("isso-author", JSON.stringify(author));
localStorage.setItem("isso-email", JSON.stringify(email));
localStorage.setItem("isso-website", JSON.stringify(website));
api.create($("#isso-thread").getAttribute("data-isso-id"), {
author: author, email: email, website: website,
text: utils.text($(".isso-textarea", el).innerHTML),
parent: parent || null,
title: $("#isso-thread").getAttribute("data-title") || null,
notification: $("[name=notification]", el).checked() ? 1 : 0,
}).then(function(comment) {
$(".isso-textarea", el).innerHTML = "";
$(".isso-textarea", el).blur();
insert(comment, true);
if (parent !== null) {
el.onsuccess();
}
});
});
editorify($(".isso-textarea", el));
return el;
};
var insert_loader = function(comment, lastcreated) {
var entrypoint;
if (comment.id === null) {
entrypoint = $("#isso-root");
comment.name = 'null';
} else {
entrypoint = $("#isso-" + comment.id + " > .isso-follow-up");
comment.name = comment.id;
}
var el = $.htmlify(template.render("comment-loader", {"comment": comment}));
entrypoint.append(el);
$("a.isso-load-hidden", el).on("click", function() {
el.remove();
api.fetch($("#isso-thread").getAttribute("data-isso-id"),
config["reveal-on-click"], config["max-comments-nested"],
comment.id,
lastcreated).then(
function(rv) {
if (rv.total_replies === 0) {
return;
}
var lastcreated = 0;
rv.replies.forEach(function(commentObject) {
insert(commentObject, false);
if(commentObject.created > lastcreated) {
lastcreated = commentObject.created;
}
});
if(rv.hidden_replies > 0) {
insert_loader(rv, lastcreated);
}
},
function(err) {
console.log(err);
});
});
};
var insert = function(comment, scrollIntoView) {
var el = $.htmlify(template.render("comment", {"comment": comment}));
// update datetime every 60 seconds
var refresh = function() {
$(".isso-permalink > time", el).textContent = i18n.ago(
globals.offset.localTime(), new Date(parseInt(comment.created, 10) * 1000));
setTimeout(refresh, 60*1000);
};
// run once to activate
refresh();
if (config["avatar"]) {
$(".isso-avatar > svg", el).replace(identicons.generate(comment.hash, 4, 48, config));
}
var entrypoint;
if (comment.parent === null) {
entrypoint = $("#isso-root");
} else {
entrypoint = $("#isso-" + comment.parent + " > .isso-follow-up");
}
entrypoint.append(el);
if (scrollIntoView) {
el.scrollIntoView();
}
var footer = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-footer"),
header = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-header"),
text = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-text");
var form = null; // XXX: probably a good place for a closure
$("a.isso-reply", footer).toggle("click",
function(toggler) {
form = footer.insertAfter(new Postbox(comment.parent === null ? comment.id : comment.parent));
form.onsuccess = function() { toggler.next(); };
$(".isso-textarea", form).focus();
$("a.isso-reply", footer).textContent = i18n.translate("comment-close");
},
function() {
form.remove();
$("a.isso-reply", footer).textContent = i18n.translate("comment-reply");
}
);
if (config.vote) {
var voteLevels = config['vote-levels'];
if (typeof voteLevels === 'string') {
// Eg. -5,5,15
voteLevels = voteLevels.split(',');
}
// update vote counter
var votes = function (value) {
var span = $("span.isso-votes", footer);
if (span === null) {
footer.prepend($.new("span.isso-votes", value));
} else {
span.textContent = value;
}
if (value) {
el.classList.remove('isso-no-votes');
} else {
el.classList.add('isso-no-votes');
}
if (voteLevels) {
var before = true;
for (var index = 0; index <= voteLevels.length; index++) {
if (before && (index >= voteLevels.length || value < voteLevels[index])) {
el.classList.add('isso-vote-level-' + index);
before = false;
} else {
el.classList.remove('isso-vote-level-' + index);
}
}
}
};
$("a.isso-upvote", footer).on("click", function () {
api.like(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
$("a.isso-downvote", footer).on("click", function () {
api.dislike(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
votes(comment.likes - comment.dislikes);
}
$("a.isso-edit", footer).toggle("click",
function(toggler) {
var edit = $("a.isso-edit", footer);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
edit.textContent = i18n.translate("comment-save");
edit.insertAfter($.new("a.isso-cancel", i18n.translate("comment-cancel"))).on("click", function() {
toggler.canceled = true;
toggler.next();
});
toggler.canceled = false;
api.view(comment.id, 1).then(function(rv) {
var textarea = editorify($.new("div.isso-textarea"));
textarea.innerHTML = utils.detext(rv.text);
textarea.focus();
text.classList.remove("isso-text");
text.classList.add("isso-textarea-wrapper");
text.textContent = "";
text.append(textarea);
});
if (avatar !== null) {
avatar.hide();
}
},
function(toggler) {
var textarea = $(".isso-textarea", text);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
if (! toggler.canceled && textarea !== null) {
if (utils.text(textarea.innerHTML).length < 3) {
textarea.focus();
toggler.wait();
return;
} else {
api.modify(comment.id, {"text": utils.text(textarea.innerHTML)}).then(function(rv) {
text.innerHTML = rv.text;
comment.text = rv.text;
});
}
} else {
text.innerHTML = comment.text;
}
text.classList.remove("isso-textarea-wrapper");
text.classList.add("isso-text");
if (avatar !== null) {
avatar.show();
}
$("a.isso-cancel", footer).remove();
$("a.isso-edit", footer).textContent = i18n.translate("comment-edit");
}
);
$("a.isso-delete", footer).toggle("click",
function(toggler) {
var del = $("a.isso-delete", footer);
var state = ! toggler.state;
del.textContent = i18n.translate("comment-confirm");
del.on("mouseout", function() {
del.textContent = i18n.translate("comment-delete");
toggler.state = state;
del.onmouseout = null;
});
},
function() {
var del = $("a.isso-delete", footer);
api.remove(comment.id).then(function(rv) {
if (rv) {
el.remove();
} else {
$("span.isso-note", header).textContent = i18n.translate("comment-deleted");
text.innerHTML = "<p> </p>";
$("a.isso-edit", footer).remove();
$("a.isso-delete", footer).remove();
}
del.textContent = i18n.translate("comment-delete");
});
}
);
// remove edit and delete buttons when cookie is gone
var clear = function(button) {
if (! utils.cookie("isso-" + comment.id)) {
if ($(button, footer) !== null) {
$(button, footer).remove();
}
} else {
setTimeout(function() { clear(button); }, 15*1000);
}
};
clear("a.isso-edit");
clear("a.isso-delete");
// show direct reply to own comment when cookie is max aged
var show = function(el) {
if (utils.cookie("isso-" + comment.id)) {
setTimeout(function() { show(el); }, 15*1000);
} else {
footer.append(el);
}
};
if (! config["reply-to-self"] && utils.cookie("isso-" + comment.id)) {
show($("a.isso-reply", footer).detach());
}
if(comment.hasOwnProperty('replies')) {
var lastcreated = 0;
comment.replies.forEach(function(replyObject) {
insert(replyObject, false);
if(replyObject.created > lastcreated) {
lastcreated = replyObject.created;
}
});
if(comment.hidden_replies > 0) {
insert_loader(comment, lastcreated);
}
}
};
module.exports = {
insert: insert,
insert_loader: insert_loader,
Postbox: Postbox,
};
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | I took a look at those docs and the other files, but I'm still not really sure what I should do to test it. It doesn't look like a similar scenario to the other tests. | BBaoVanC | 47 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/js/app/isso.js | /* Isso – Ich schrei sonst!
*/
var $ = require("app/dom");
var utils = require("app/utils");
var config = require("app/config");
var api = require("app/api");
var template = require("app/template");
var i18n = require("app/i18n");
var identicons = require("app/lib/identicons");
var globals = require("app/globals");
"use strict";
var editorify = function(el) {
el = $.htmlify(el);
el.setAttribute("contentEditable", true);
el.on("focus", function() {
if (el.classList.contains("isso-placeholder")) {
el.innerHTML = "";
el.classList.remove("isso-placeholder");
}
});
el.on("blur", function() {
if (el.textContent.length === 0) {
el.textContent = i18n.translate("postbox-text");
el.classList.add("isso-placeholder");
}
});
return el;
}
var Postbox = function(parent) {
var localStorage = utils.localStorageImpl,
el = $.htmlify(template.render("postbox", {
"author": JSON.parse(localStorage.getItem("isso-author")),
"email": JSON.parse(localStorage.getItem("isso-email")),
"website": JSON.parse(localStorage.getItem("isso-website")),
"preview": ''
}));
// callback on success (e.g. to toggle the reply button)
el.onsuccess = function() {};
el.validate = function() {
if (utils.text($(".isso-textarea", this).innerHTML).length < 3 ||
$(".isso-textarea", this).classList.contains("isso-placeholder"))
{
$(".isso-textarea", this).focus();
return false;
}
if (config["require-email"] &&
$("[name='email']", this).value.length <= 0)
{
$("[name='email']", this).focus();
return false;
}
if (config["require-author"] &&
$("[name='author']", this).value.length <= 0)
{
$("[name='author']", this).focus();
return false;
}
return true;
};
// only display notification checkbox if email is filled in
var email_edit = function() {
if (config["reply-notifications"] && $("[name='email']", el).value.length > 0) {
$(".isso-notification-section", el).show();
} else {
$(".isso-notification-section", el).hide();
}
};
$("[name='email']", el).on("input", email_edit);
email_edit();
// email is not optional if this config parameter is set
if (config["require-email"]) {
$("[for='isso-postbox-email']", el).textContent =
$("[for='isso-postbox-email']", el).textContent.replace(/ \(.*\)/, "");
}
// author is not optional if this config parameter is set
if (config["require-author"]) {
$("[for='isso-postbox-author']", el).textContent =
$("[for='isso-postbox-author']", el).textContent.replace(/ \(.*\)/, "");
}
// preview function
$("[name='preview']", el).on("click", function() {
api.preview(utils.text($(".isso-textarea", el).innerHTML)).then(
function(html) {
$(".isso-preview .isso-text", el).innerHTML = html;
el.classList.add('isso-preview-mode');
});
});
// edit function
var edit = function() {
$(".isso-preview .isso-text", el).innerHTML = '';
el.classList.remove('isso-preview-mode');
};
$("[name='edit']", el).on("click", edit);
$(".isso-preview", el).on("click", edit);
// submit form, initialize optional fields with `null` and reset form.
// If replied to a comment, remove form completely.
$("[type=submit]", el).on("click", function() {
edit();
if (! el.validate()) {
return;
}
var author = $("[name=author]", el).value || null,
email = $("[name=email]", el).value || null,
website = $("[name=website]", el).value || null;
localStorage.setItem("isso-author", JSON.stringify(author));
localStorage.setItem("isso-email", JSON.stringify(email));
localStorage.setItem("isso-website", JSON.stringify(website));
api.create($("#isso-thread").getAttribute("data-isso-id"), {
author: author, email: email, website: website,
text: utils.text($(".isso-textarea", el).innerHTML),
parent: parent || null,
title: $("#isso-thread").getAttribute("data-title") || null,
notification: $("[name=notification]", el).checked() ? 1 : 0,
}).then(function(comment) {
$(".isso-textarea", el).innerHTML = "";
$(".isso-textarea", el).blur();
insert(comment, true);
if (parent !== null) {
el.onsuccess();
}
});
});
editorify($(".isso-textarea", el));
return el;
};
var insert_loader = function(comment, lastcreated) {
var entrypoint;
if (comment.id === null) {
entrypoint = $("#isso-root");
comment.name = 'null';
} else {
entrypoint = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-follow-up");
comment.name = comment.id;
}
var el = $.htmlify(template.render("comment-loader", {"comment": comment}));
entrypoint.append(el);
$("a.isso-load-hidden", el).on("click", function() {
el.remove();
api.fetch($("#isso-thread").getAttribute("data-isso-id"),
config["reveal-on-click"], config["max-comments-nested"],
comment.id,
lastcreated).then(
function(rv) {
if (rv.total_replies === 0) {
return;
}
var lastcreated = 0;
rv.replies.forEach(function(commentObject) {
insert(commentObject, false);
if(commentObject.created > lastcreated) {
lastcreated = commentObject.created;
}
});
if(rv.hidden_replies > 0) {
insert_loader(rv, lastcreated);
}
},
function(err) {
console.log(err);
});
});
};
var insert = function(comment, scrollIntoView) {
var el = $.htmlify(template.render("comment", {"comment": comment}));
// update datetime every 60 seconds
var refresh = function() {
$(".isso-permalink > time", el).textContent = i18n.ago(
globals.offset.localTime(), new Date(parseInt(comment.created, 10) * 1000));
setTimeout(refresh, 60*1000);
};
// run once to activate
refresh();
if (config["avatar"]) {
$(".isso-avatar > svg", el).replace(identicons.generate(comment.hash, 4, 48, config));
}
var entrypoint;
if (comment.parent === null) {
entrypoint = $("#isso-root");
} else {
entrypoint = $("#isso-" + comment.parent + " > .isso-text-wrapper > .isso-follow-up");
}
entrypoint.append(el);
if (scrollIntoView) {
el.scrollIntoView();
}
var footer = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-footer"),
header = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-header"),
text = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-text");
var form = null; // XXX: probably a good place for a closure
$("a.isso-reply", footer).toggle("click",
function(toggler) {
form = footer.insertAfter(new Postbox(comment.parent === null ? comment.id : comment.parent));
form.onsuccess = function() { toggler.next(); };
$(".isso-textarea", form).focus();
$("a.isso-reply", footer).textContent = i18n.translate("comment-close");
},
function() {
form.remove();
$("a.isso-reply", footer).textContent = i18n.translate("comment-reply");
}
);
if (config.vote) {
var voteLevels = config['vote-levels'];
if (typeof voteLevels === 'string') {
// Eg. -5,5,15
voteLevels = voteLevels.split(',');
}
// update vote counter
var votes = function (value) {
var span = $("span.isso-votes", footer);
if (span === null) {
footer.prepend($.new("span.isso-votes", value));
} else {
span.textContent = value;
}
if (value) {
el.classList.remove('isso-no-votes');
} else {
el.classList.add('isso-no-votes');
}
if (voteLevels) {
var before = true;
for (var index = 0; index <= voteLevels.length; index++) {
if (before && (index >= voteLevels.length || value < voteLevels[index])) {
el.classList.add('isso-vote-level-' + index);
before = false;
} else {
el.classList.remove('isso-vote-level-' + index);
}
}
}
};
$("a.isso-upvote", footer).on("click", function () {
api.like(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
$("a.isso-downvote", footer).on("click", function () {
api.dislike(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
votes(comment.likes - comment.dislikes);
}
$("a.isso-edit", footer).toggle("click",
function(toggler) {
var edit = $("a.isso-edit", footer);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
edit.textContent = i18n.translate("comment-save");
edit.insertAfter($.new("a.isso-cancel", i18n.translate("comment-cancel"))).on("click", function() {
toggler.canceled = true;
toggler.next();
});
toggler.canceled = false;
api.view(comment.id, 1).then(function(rv) {
var textarea = editorify($.new("div.isso-textarea"));
textarea.innerHTML = utils.detext(rv.text);
textarea.focus();
text.classList.remove("isso-text");
text.classList.add("isso-textarea-wrapper");
text.textContent = "";
text.append(textarea);
});
if (avatar !== null) {
avatar.hide();
}
},
function(toggler) {
var textarea = $(".isso-textarea", text);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
if (! toggler.canceled && textarea !== null) {
if (utils.text(textarea.innerHTML).length < 3) {
textarea.focus();
toggler.wait();
return;
} else {
api.modify(comment.id, {"text": utils.text(textarea.innerHTML)}).then(function(rv) {
text.innerHTML = rv.text;
comment.text = rv.text;
});
}
} else {
text.innerHTML = comment.text;
}
text.classList.remove("isso-textarea-wrapper");
text.classList.add("isso-text");
if (avatar !== null) {
avatar.show();
}
$("a.isso-cancel", footer).remove();
$("a.isso-edit", footer).textContent = i18n.translate("comment-edit");
}
);
$("a.isso-delete", footer).toggle("click",
function(toggler) {
var del = $("a.isso-delete", footer);
var state = ! toggler.state;
del.textContent = i18n.translate("comment-confirm");
del.on("mouseout", function() {
del.textContent = i18n.translate("comment-delete");
toggler.state = state;
del.onmouseout = null;
});
},
function() {
var del = $("a.isso-delete", footer);
api.remove(comment.id).then(function(rv) {
if (rv) {
el.remove();
} else {
$("span.isso-note", header).textContent = i18n.translate("comment-deleted");
text.innerHTML = "<p> </p>";
$("a.isso-edit", footer).remove();
$("a.isso-delete", footer).remove();
}
del.textContent = i18n.translate("comment-delete");
});
}
);
// remove edit and delete buttons when cookie is gone
var clear = function(button) {
if (! utils.cookie("isso-" + comment.id)) {
if ($(button, footer) !== null) {
$(button, footer).remove();
}
} else {
setTimeout(function() { clear(button); }, 15*1000);
}
};
clear("a.isso-edit");
clear("a.isso-delete");
// show direct reply to own comment when cookie is max aged
var show = function(el) {
if (utils.cookie("isso-" + comment.id)) {
setTimeout(function() { show(el); }, 15*1000);
} else {
footer.append(el);
}
};
if (! config["reply-to-self"] && utils.cookie("isso-" + comment.id)) {
show($("a.isso-reply", footer).detach());
}
if(comment.hasOwnProperty('replies')) {
var lastcreated = 0;
comment.replies.forEach(function(replyObject) {
insert(replyObject, false);
if(replyObject.created > lastcreated) {
lastcreated = replyObject.created;
}
});
if(comment.hidden_replies > 0) {
insert_loader(comment, lastcreated);
}
}
};
module.exports = {
insert: insert,
insert_loader: insert_loader,
Postbox: Postbox,
};
| /* Isso – Ich schrei sonst!
*/
var $ = require("app/dom");
var utils = require("app/utils");
var config = require("app/config");
var api = require("app/api");
var template = require("app/template");
var i18n = require("app/i18n");
var identicons = require("app/lib/identicons");
var globals = require("app/globals");
"use strict";
var editorify = function(el) {
el = $.htmlify(el);
el.setAttribute("contentEditable", true);
el.on("focus", function() {
if (el.classList.contains("isso-placeholder")) {
el.innerHTML = "";
el.classList.remove("isso-placeholder");
}
});
el.on("blur", function() {
if (el.textContent.length === 0) {
el.textContent = i18n.translate("postbox-text");
el.classList.add("isso-placeholder");
}
});
return el;
}
var Postbox = function(parent) {
var localStorage = utils.localStorageImpl,
el = $.htmlify(template.render("postbox", {
"author": JSON.parse(localStorage.getItem("isso-author")),
"email": JSON.parse(localStorage.getItem("isso-email")),
"website": JSON.parse(localStorage.getItem("isso-website")),
"preview": ''
}));
// callback on success (e.g. to toggle the reply button)
el.onsuccess = function() {};
el.validate = function() {
if (utils.text($(".isso-textarea", this).innerHTML).length < 3 ||
$(".isso-textarea", this).classList.contains("isso-placeholder"))
{
$(".isso-textarea", this).focus();
return false;
}
if (config["require-email"] &&
$("[name='email']", this).value.length <= 0)
{
$("[name='email']", this).focus();
return false;
}
if (config["require-author"] &&
$("[name='author']", this).value.length <= 0)
{
$("[name='author']", this).focus();
return false;
}
return true;
};
// only display notification checkbox if email is filled in
var email_edit = function() {
if (config["reply-notifications"] && $("[name='email']", el).value.length > 0) {
$(".isso-notification-section", el).show();
} else {
$(".isso-notification-section", el).hide();
}
};
$("[name='email']", el).on("input", email_edit);
email_edit();
// email is not optional if this config parameter is set
if (config["require-email"]) {
$("[for='isso-postbox-email']", el).textContent =
$("[for='isso-postbox-email']", el).textContent.replace(/ \(.*\)/, "");
}
// author is not optional if this config parameter is set
if (config["require-author"]) {
$("[for='isso-postbox-author']", el).textContent =
$("[for='isso-postbox-author']", el).textContent.replace(/ \(.*\)/, "");
}
// preview function
$("[name='preview']", el).on("click", function() {
api.preview(utils.text($(".isso-textarea", el).innerHTML)).then(
function(html) {
$(".isso-preview .isso-text", el).innerHTML = html;
el.classList.add('isso-preview-mode');
});
});
// edit function
var edit = function() {
$(".isso-preview .isso-text", el).innerHTML = '';
el.classList.remove('isso-preview-mode');
};
$("[name='edit']", el).on("click", edit);
$(".isso-preview", el).on("click", edit);
// submit form, initialize optional fields with `null` and reset form.
// If replied to a comment, remove form completely.
$("[type=submit]", el).on("click", function() {
edit();
if (! el.validate()) {
return;
}
var author = $("[name=author]", el).value || null,
email = $("[name=email]", el).value || null,
website = $("[name=website]", el).value || null;
localStorage.setItem("isso-author", JSON.stringify(author));
localStorage.setItem("isso-email", JSON.stringify(email));
localStorage.setItem("isso-website", JSON.stringify(website));
api.create($("#isso-thread").getAttribute("data-isso-id"), {
author: author, email: email, website: website,
text: utils.text($(".isso-textarea", el).innerHTML),
parent: parent || null,
title: $("#isso-thread").getAttribute("data-title") || null,
notification: $("[name=notification]", el).checked() ? 1 : 0,
}).then(function(comment) {
$(".isso-textarea", el).innerHTML = "";
$(".isso-textarea", el).blur();
insert(comment, true);
if (parent !== null) {
el.onsuccess();
}
});
});
editorify($(".isso-textarea", el));
return el;
};
var insert_loader = function(comment, lastcreated) {
var entrypoint;
if (comment.id === null) {
entrypoint = $("#isso-root");
comment.name = 'null';
} else {
entrypoint = $("#isso-" + comment.id + " > .isso-follow-up");
comment.name = comment.id;
}
var el = $.htmlify(template.render("comment-loader", {"comment": comment}));
entrypoint.append(el);
$("a.isso-load-hidden", el).on("click", function() {
el.remove();
api.fetch($("#isso-thread").getAttribute("data-isso-id"),
config["reveal-on-click"], config["max-comments-nested"],
comment.id,
lastcreated).then(
function(rv) {
if (rv.total_replies === 0) {
return;
}
var lastcreated = 0;
rv.replies.forEach(function(commentObject) {
insert(commentObject, false);
if(commentObject.created > lastcreated) {
lastcreated = commentObject.created;
}
});
if(rv.hidden_replies > 0) {
insert_loader(rv, lastcreated);
}
},
function(err) {
console.log(err);
});
});
};
var insert = function(comment, scrollIntoView) {
var el = $.htmlify(template.render("comment", {"comment": comment}));
// update datetime every 60 seconds
var refresh = function() {
$(".isso-permalink > time", el).textContent = i18n.ago(
globals.offset.localTime(), new Date(parseInt(comment.created, 10) * 1000));
setTimeout(refresh, 60*1000);
};
// run once to activate
refresh();
if (config["avatar"]) {
$(".isso-avatar > svg", el).replace(identicons.generate(comment.hash, 4, 48, config));
}
var entrypoint;
if (comment.parent === null) {
entrypoint = $("#isso-root");
} else {
entrypoint = $("#isso-" + comment.parent + " > .isso-follow-up");
}
entrypoint.append(el);
if (scrollIntoView) {
el.scrollIntoView();
}
var footer = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-footer"),
header = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-comment-header"),
text = $("#isso-" + comment.id + " > .isso-text-wrapper > .isso-text");
var form = null; // XXX: probably a good place for a closure
$("a.isso-reply", footer).toggle("click",
function(toggler) {
form = footer.insertAfter(new Postbox(comment.parent === null ? comment.id : comment.parent));
form.onsuccess = function() { toggler.next(); };
$(".isso-textarea", form).focus();
$("a.isso-reply", footer).textContent = i18n.translate("comment-close");
},
function() {
form.remove();
$("a.isso-reply", footer).textContent = i18n.translate("comment-reply");
}
);
if (config.vote) {
var voteLevels = config['vote-levels'];
if (typeof voteLevels === 'string') {
// Eg. -5,5,15
voteLevels = voteLevels.split(',');
}
// update vote counter
var votes = function (value) {
var span = $("span.isso-votes", footer);
if (span === null) {
footer.prepend($.new("span.isso-votes", value));
} else {
span.textContent = value;
}
if (value) {
el.classList.remove('isso-no-votes');
} else {
el.classList.add('isso-no-votes');
}
if (voteLevels) {
var before = true;
for (var index = 0; index <= voteLevels.length; index++) {
if (before && (index >= voteLevels.length || value < voteLevels[index])) {
el.classList.add('isso-vote-level-' + index);
before = false;
} else {
el.classList.remove('isso-vote-level-' + index);
}
}
}
};
$("a.isso-upvote", footer).on("click", function () {
api.like(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
$("a.isso-downvote", footer).on("click", function () {
api.dislike(comment.id).then(function (rv) {
votes(rv.likes - rv.dislikes);
});
});
votes(comment.likes - comment.dislikes);
}
$("a.isso-edit", footer).toggle("click",
function(toggler) {
var edit = $("a.isso-edit", footer);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
edit.textContent = i18n.translate("comment-save");
edit.insertAfter($.new("a.isso-cancel", i18n.translate("comment-cancel"))).on("click", function() {
toggler.canceled = true;
toggler.next();
});
toggler.canceled = false;
api.view(comment.id, 1).then(function(rv) {
var textarea = editorify($.new("div.isso-textarea"));
textarea.innerHTML = utils.detext(rv.text);
textarea.focus();
text.classList.remove("isso-text");
text.classList.add("isso-textarea-wrapper");
text.textContent = "";
text.append(textarea);
});
if (avatar !== null) {
avatar.hide();
}
},
function(toggler) {
var textarea = $(".isso-textarea", text);
var avatar = config["avatar"] || config["gravatar"] ? $(".isso-avatar", el, false)[0] : null;
if (! toggler.canceled && textarea !== null) {
if (utils.text(textarea.innerHTML).length < 3) {
textarea.focus();
toggler.wait();
return;
} else {
api.modify(comment.id, {"text": utils.text(textarea.innerHTML)}).then(function(rv) {
text.innerHTML = rv.text;
comment.text = rv.text;
});
}
} else {
text.innerHTML = comment.text;
}
text.classList.remove("isso-textarea-wrapper");
text.classList.add("isso-text");
if (avatar !== null) {
avatar.show();
}
$("a.isso-cancel", footer).remove();
$("a.isso-edit", footer).textContent = i18n.translate("comment-edit");
}
);
$("a.isso-delete", footer).toggle("click",
function(toggler) {
var del = $("a.isso-delete", footer);
var state = ! toggler.state;
del.textContent = i18n.translate("comment-confirm");
del.on("mouseout", function() {
del.textContent = i18n.translate("comment-delete");
toggler.state = state;
del.onmouseout = null;
});
},
function() {
var del = $("a.isso-delete", footer);
api.remove(comment.id).then(function(rv) {
if (rv) {
el.remove();
} else {
$("span.isso-note", header).textContent = i18n.translate("comment-deleted");
text.innerHTML = "<p> </p>";
$("a.isso-edit", footer).remove();
$("a.isso-delete", footer).remove();
}
del.textContent = i18n.translate("comment-delete");
});
}
);
// remove edit and delete buttons when cookie is gone
var clear = function(button) {
if (! utils.cookie("isso-" + comment.id)) {
if ($(button, footer) !== null) {
$(button, footer).remove();
}
} else {
setTimeout(function() { clear(button); }, 15*1000);
}
};
clear("a.isso-edit");
clear("a.isso-delete");
// show direct reply to own comment when cookie is max aged
var show = function(el) {
if (utils.cookie("isso-" + comment.id)) {
setTimeout(function() { show(el); }, 15*1000);
} else {
footer.append(el);
}
};
if (! config["reply-to-self"] && utils.cookie("isso-" + comment.id)) {
show($("a.isso-reply", footer).detach());
}
if(comment.hasOwnProperty('replies')) {
var lastcreated = 0;
comment.replies.forEach(function(replyObject) {
insert(replyObject, false);
if(replyObject.created > lastcreated) {
lastcreated = replyObject.created;
}
});
if(comment.hidden_replies > 0) {
insert_loader(comment, lastcreated);
}
}
};
module.exports = {
insert: insert,
insert_loader: insert_loader,
Postbox: Postbox,
};
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | I'll write a test for it myself. | ix5 | 48 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/js/app/templates/comment.js | var html = function (globals) {
var i18n = globals.i18n;
var comment = globals.comment;
var conf = globals.conf;
var datetime = globals.datetime;
var humanize = globals.humanize;
var svg = globals.svg;
var author = comment.author ? comment.author : i18n('comment-anonymous');
return "" +
"<div class='isso-comment' id='isso-" + comment.id + "'>"
+ (conf.gravatar ? "<div class='isso-avatar'><img src='" + comment.gravatar_image + "'></div>" : '')
+ (conf.avatar ? "<div class='isso-avatar'><svg data-hash='" + comment.hash + "'</svg></div>" : '')
+ "<div class='isso-text-wrapper'>"
+ "<div class='isso-comment-header' role='meta'>"
+ (comment.website
? "<a class='isso-author' href='" + comment.website + "' rel='nofollow'>" + author + "</a>"
: "<span class='isso-author'>" + author + "</span>")
+ "<span class='isso-spacer'>•</span>"
+ "<a class='isso-permalink' href='#isso-" + comment.id + "'>"
+ "<time title='" + humanize(comment.created) + "' datetime='" + datetime(comment.created) + "'>" + humanize(comment.created) + "</time>"
+ "</a>"
+ "<span class='isso-note'>"
+ (comment.mode == 2 ? i18n('comment-queued') : (comment.mode == 4 ? i18n('comment-deleted') : ''))
+ "</span>"
+ "</div>" // .text-wrapper
+ "<div class='isso-text'>"
+ (comment.mode == 4 ? '<p> </p>' : comment.text)
+ "</div>" // .text
+ "<div class='isso-comment-footer'>"
+ (conf.vote
? "<a class='isso-upvote' href='#'>" + svg['arrow-up'] + "</a>"
+ "<span class='isso-spacer'>|</span>"
+ "<a class='isso-downvote' href='#'>" + svg['arrow-down'] + "</a>"
: '')
+ "<a class='isso-reply' href='#'>" + i18n('comment-reply') + "</a>"
+ "<a class='isso-edit' href='#'>" + i18n('comment-edit') + "</a>"
+ "<a class='isso-delete' href='#'>" + i18n('comment-delete') + "</a>"
+ "</div>" // .isso-comment-footer
+ "<div class='isso-follow-up'></div>"
+ "</div>" // .text-wrapper
+ "</div>" // .isso-comment
};
module.exports = html;
| var html = function (globals) {
var i18n = globals.i18n;
var comment = globals.comment;
var conf = globals.conf;
var datetime = globals.datetime;
var humanize = globals.humanize;
var svg = globals.svg;
var author = comment.author ? comment.author : i18n('comment-anonymous');
var isPageAuthor = conf["page-author-hashes"].indexOf(comment.hash) > -1;
var pageAuthorClass = (isPageAuthor ? " isso-is-page-author" : '');
return "" +
"<div class='isso-comment" + pageAuthorClass + "' id='isso-" + comment.id + "' data-hash='" + comment.hash + "'>"
+ (conf.gravatar ? "<div class='isso-avatar'><img src='" + comment.gravatar_image + "'></div>" : '')
+ (conf.avatar ? "<div class='isso-avatar'><svg data-hash='" + comment.hash + "'</svg></div>" : '')
+ "<div class='isso-text-wrapper'>"
+ "<div class='isso-comment-header' role='meta'>"
+ (comment.website
? "<a class='isso-author' href='" + comment.website + "' rel='nofollow'>" + author + "</a>"
: "<span class='isso-author'>" + author + "</span>")
+ (isPageAuthor
? "<span class='isso-spacer'>•</span>"
+ "<span class='isso-page-author-suffix'>" + i18n('comment-page-author-suffix') + "</span>"
: '' )
+ "<span class='isso-spacer'>•</span>"
+ "<a class='isso-permalink' href='#isso-" + comment.id + "'>"
+ "<time title='" + humanize(comment.created) + "' datetime='" + datetime(comment.created) + "'>" + humanize(comment.created) + "</time>"
+ "</a>"
+ "<span class='isso-note'>"
+ (comment.mode == 2 ? i18n('comment-queued') : (comment.mode == 4 ? i18n('comment-deleted') : ''))
+ "</span>"
+ "</div>" // .text-wrapper
+ "<div class='isso-text'>"
+ (comment.mode == 4 ? '<p> </p>' : comment.text)
+ "</div>" // .text
+ "<div class='isso-comment-footer'>"
+ (conf.vote
? "<a class='isso-upvote' href='#'>" + svg['arrow-up'] + "</a>"
+ "<span class='isso-spacer'>|</span>"
+ "<a class='isso-downvote' href='#'>" + svg['arrow-down'] + "</a>"
: '')
+ "<a class='isso-reply' href='#'>" + i18n('comment-reply') + "</a>"
+ "<a class='isso-edit' href='#'>" + i18n('comment-edit') + "</a>"
+ "<a class='isso-delete' href='#'>" + i18n('comment-delete') + "</a>"
+ "</div>" // .isso-comment-footer
+ "</div>" // .text-wrapper
+ "<div class='isso-follow-up'></div>"
+ "</div>" // .isso-comment
};
module.exports = html;
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | `isso-is-page-author` instead? (implying that it's kind of a boolean to CSS editors) | ix5 | 49 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/js/app/templates/comment.js | var html = function (globals) {
var i18n = globals.i18n;
var comment = globals.comment;
var conf = globals.conf;
var datetime = globals.datetime;
var humanize = globals.humanize;
var svg = globals.svg;
var author = comment.author ? comment.author : i18n('comment-anonymous');
return "" +
"<div class='isso-comment' id='isso-" + comment.id + "'>"
+ (conf.gravatar ? "<div class='isso-avatar'><img src='" + comment.gravatar_image + "'></div>" : '')
+ (conf.avatar ? "<div class='isso-avatar'><svg data-hash='" + comment.hash + "'</svg></div>" : '')
+ "<div class='isso-text-wrapper'>"
+ "<div class='isso-comment-header' role='meta'>"
+ (comment.website
? "<a class='isso-author' href='" + comment.website + "' rel='nofollow'>" + author + "</a>"
: "<span class='isso-author'>" + author + "</span>")
+ "<span class='isso-spacer'>•</span>"
+ "<a class='isso-permalink' href='#isso-" + comment.id + "'>"
+ "<time title='" + humanize(comment.created) + "' datetime='" + datetime(comment.created) + "'>" + humanize(comment.created) + "</time>"
+ "</a>"
+ "<span class='isso-note'>"
+ (comment.mode == 2 ? i18n('comment-queued') : (comment.mode == 4 ? i18n('comment-deleted') : ''))
+ "</span>"
+ "</div>" // .text-wrapper
+ "<div class='isso-text'>"
+ (comment.mode == 4 ? '<p> </p>' : comment.text)
+ "</div>" // .text
+ "<div class='isso-comment-footer'>"
+ (conf.vote
? "<a class='isso-upvote' href='#'>" + svg['arrow-up'] + "</a>"
+ "<span class='isso-spacer'>|</span>"
+ "<a class='isso-downvote' href='#'>" + svg['arrow-down'] + "</a>"
: '')
+ "<a class='isso-reply' href='#'>" + i18n('comment-reply') + "</a>"
+ "<a class='isso-edit' href='#'>" + i18n('comment-edit') + "</a>"
+ "<a class='isso-delete' href='#'>" + i18n('comment-delete') + "</a>"
+ "</div>" // .isso-comment-footer
+ "<div class='isso-follow-up'></div>"
+ "</div>" // .text-wrapper
+ "</div>" // .isso-comment
};
module.exports = html;
| var html = function (globals) {
var i18n = globals.i18n;
var comment = globals.comment;
var conf = globals.conf;
var datetime = globals.datetime;
var humanize = globals.humanize;
var svg = globals.svg;
var author = comment.author ? comment.author : i18n('comment-anonymous');
var isPageAuthor = conf["page-author-hashes"].indexOf(comment.hash) > -1;
var pageAuthorClass = (isPageAuthor ? " isso-is-page-author" : '');
return "" +
"<div class='isso-comment" + pageAuthorClass + "' id='isso-" + comment.id + "' data-hash='" + comment.hash + "'>"
+ (conf.gravatar ? "<div class='isso-avatar'><img src='" + comment.gravatar_image + "'></div>" : '')
+ (conf.avatar ? "<div class='isso-avatar'><svg data-hash='" + comment.hash + "'</svg></div>" : '')
+ "<div class='isso-text-wrapper'>"
+ "<div class='isso-comment-header' role='meta'>"
+ (comment.website
? "<a class='isso-author' href='" + comment.website + "' rel='nofollow'>" + author + "</a>"
: "<span class='isso-author'>" + author + "</span>")
+ (isPageAuthor
? "<span class='isso-spacer'>•</span>"
+ "<span class='isso-page-author-suffix'>" + i18n('comment-page-author-suffix') + "</span>"
: '' )
+ "<span class='isso-spacer'>•</span>"
+ "<a class='isso-permalink' href='#isso-" + comment.id + "'>"
+ "<time title='" + humanize(comment.created) + "' datetime='" + datetime(comment.created) + "'>" + humanize(comment.created) + "</time>"
+ "</a>"
+ "<span class='isso-note'>"
+ (comment.mode == 2 ? i18n('comment-queued') : (comment.mode == 4 ? i18n('comment-deleted') : ''))
+ "</span>"
+ "</div>" // .text-wrapper
+ "<div class='isso-text'>"
+ (comment.mode == 4 ? '<p> </p>' : comment.text)
+ "</div>" // .text
+ "<div class='isso-comment-footer'>"
+ (conf.vote
? "<a class='isso-upvote' href='#'>" + svg['arrow-up'] + "</a>"
+ "<span class='isso-spacer'>|</span>"
+ "<a class='isso-downvote' href='#'>" + svg['arrow-down'] + "</a>"
: '')
+ "<a class='isso-reply' href='#'>" + i18n('comment-reply') + "</a>"
+ "<a class='isso-edit' href='#'>" + i18n('comment-edit') + "</a>"
+ "<a class='isso-delete' href='#'>" + i18n('comment-delete') + "</a>"
+ "</div>" // .isso-comment-footer
+ "</div>" // .text-wrapper
+ "<div class='isso-follow-up'></div>"
+ "</div>" // .isso-comment
};
module.exports = html;
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | This is a string that must be translated. Add it to `i18n/en.js` (and - in a separate commit - to any other translation files of languages you speak)
~~Also, I think we might have a problem with right-to-left languages. With e.g. `Amir` + ` (Author)` in Arabic (`أمير` and `(مؤلف)`, this should be `أمير (مؤلف)`~~ Huh, Javascript apparently already does the correct thing for us and keeps the Arabic part RTL, but the latin part ltr. Nice. | ix5 | 50 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/js/app/templates/comment.js | var html = function (globals) {
var i18n = globals.i18n;
var comment = globals.comment;
var conf = globals.conf;
var datetime = globals.datetime;
var humanize = globals.humanize;
var svg = globals.svg;
var author = comment.author ? comment.author : i18n('comment-anonymous');
return "" +
"<div class='isso-comment' id='isso-" + comment.id + "'>"
+ (conf.gravatar ? "<div class='isso-avatar'><img src='" + comment.gravatar_image + "'></div>" : '')
+ (conf.avatar ? "<div class='isso-avatar'><svg data-hash='" + comment.hash + "'</svg></div>" : '')
+ "<div class='isso-text-wrapper'>"
+ "<div class='isso-comment-header' role='meta'>"
+ (comment.website
? "<a class='isso-author' href='" + comment.website + "' rel='nofollow'>" + author + "</a>"
: "<span class='isso-author'>" + author + "</span>")
+ "<span class='isso-spacer'>•</span>"
+ "<a class='isso-permalink' href='#isso-" + comment.id + "'>"
+ "<time title='" + humanize(comment.created) + "' datetime='" + datetime(comment.created) + "'>" + humanize(comment.created) + "</time>"
+ "</a>"
+ "<span class='isso-note'>"
+ (comment.mode == 2 ? i18n('comment-queued') : (comment.mode == 4 ? i18n('comment-deleted') : ''))
+ "</span>"
+ "</div>" // .text-wrapper
+ "<div class='isso-text'>"
+ (comment.mode == 4 ? '<p> </p>' : comment.text)
+ "</div>" // .text
+ "<div class='isso-comment-footer'>"
+ (conf.vote
? "<a class='isso-upvote' href='#'>" + svg['arrow-up'] + "</a>"
+ "<span class='isso-spacer'>|</span>"
+ "<a class='isso-downvote' href='#'>" + svg['arrow-down'] + "</a>"
: '')
+ "<a class='isso-reply' href='#'>" + i18n('comment-reply') + "</a>"
+ "<a class='isso-edit' href='#'>" + i18n('comment-edit') + "</a>"
+ "<a class='isso-delete' href='#'>" + i18n('comment-delete') + "</a>"
+ "</div>" // .isso-comment-footer
+ "<div class='isso-follow-up'></div>"
+ "</div>" // .text-wrapper
+ "</div>" // .isso-comment
};
module.exports = html;
| var html = function (globals) {
var i18n = globals.i18n;
var comment = globals.comment;
var conf = globals.conf;
var datetime = globals.datetime;
var humanize = globals.humanize;
var svg = globals.svg;
var author = comment.author ? comment.author : i18n('comment-anonymous');
var isPageAuthor = conf["page-author-hashes"].indexOf(comment.hash) > -1;
var pageAuthorClass = (isPageAuthor ? " isso-is-page-author" : '');
return "" +
"<div class='isso-comment" + pageAuthorClass + "' id='isso-" + comment.id + "' data-hash='" + comment.hash + "'>"
+ (conf.gravatar ? "<div class='isso-avatar'><img src='" + comment.gravatar_image + "'></div>" : '')
+ (conf.avatar ? "<div class='isso-avatar'><svg data-hash='" + comment.hash + "'</svg></div>" : '')
+ "<div class='isso-text-wrapper'>"
+ "<div class='isso-comment-header' role='meta'>"
+ (comment.website
? "<a class='isso-author' href='" + comment.website + "' rel='nofollow'>" + author + "</a>"
: "<span class='isso-author'>" + author + "</span>")
+ (isPageAuthor
? "<span class='isso-spacer'>•</span>"
+ "<span class='isso-page-author-suffix'>" + i18n('comment-page-author-suffix') + "</span>"
: '' )
+ "<span class='isso-spacer'>•</span>"
+ "<a class='isso-permalink' href='#isso-" + comment.id + "'>"
+ "<time title='" + humanize(comment.created) + "' datetime='" + datetime(comment.created) + "'>" + humanize(comment.created) + "</time>"
+ "</a>"
+ "<span class='isso-note'>"
+ (comment.mode == 2 ? i18n('comment-queued') : (comment.mode == 4 ? i18n('comment-deleted') : ''))
+ "</span>"
+ "</div>" // .text-wrapper
+ "<div class='isso-text'>"
+ (comment.mode == 4 ? '<p> </p>' : comment.text)
+ "</div>" // .text
+ "<div class='isso-comment-footer'>"
+ (conf.vote
? "<a class='isso-upvote' href='#'>" + svg['arrow-up'] + "</a>"
+ "<span class='isso-spacer'>|</span>"
+ "<a class='isso-downvote' href='#'>" + svg['arrow-down'] + "</a>"
: '')
+ "<a class='isso-reply' href='#'>" + i18n('comment-reply') + "</a>"
+ "<a class='isso-edit' href='#'>" + i18n('comment-edit') + "</a>"
+ "<a class='isso-delete' href='#'>" + i18n('comment-delete') + "</a>"
+ "</div>" // .isso-comment-footer
+ "</div>" // .text-wrapper
+ "<div class='isso-follow-up'></div>"
+ "</div>" // .isso-comment
};
module.exports = html;
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | Also, the ` (Author)` part should have a different color (and be a separate `span` or whatever element). Otherwise, it wouldn't stick out
And everyone could just type in `BBao (Author)` into the comment box - you'd probably catch it when manually unlocking comments, but still annoying for people without moderation turned on. | ix5 | 51 |
posativ/isso | 844 | Make it possible to identify the page author's comments | Fixes #82
## TODO
- [x] Documentation
- [x] CHANGES.rst entry
- [x] Possibly remove the colors and instead explain how to change them in the docs
- [x] Screenshot using default Isso theme
## Summary of changes
- Page author's comments will have a different background
- Their name will have a different color
- Configured using `data-isso-page-author-hashes` field in the `<script>` tag; this can include multiple hashes.
- Add matching CSS rules, and change the margin/padding rules a bit to make `.isso-text-wrapper` take up the comment's size
- Move `.isso-follow-up` div outside of `.isso-text-wrapper`
Screenshot at the bottom of this description.
## Moving `.isso-follow-up`
I moved the `.isso-follow-up` div to be outside of `.isso-text-wrapper` (so it is instead a direct child of `.isso-comment`). Then I gave the background color to the `.isso-text-wrapper`. Without this change, if someone else replies to a comment by the page author, their comment still has the background. This is because the `.isso-text-wrapper` div would be as big as the parent comment plus the follow-up ones, and the follow-up comments have a transparent background (instead of explicitly setting one).
I couldn't think of any better solution.
Luckily this change only required [changing a couple lines in `isso.js`](https://github.com/posativ/isso/pull/844/files#diff-34a9f4a1ee05a7d28372e0370d8f38e273f1b97dc84c0b943ae9916c5f16995c) so it would properly match the new location.
## Configuring
Configure by setting the `data-isso-page-author-hashes` variable to the hash of the user (or a list of them) that should be highlighted. If providing multiple, separate them with a comma, space, or both.
For example, these all work (I made up the hashes though):
- `data-isso-page-author-hashes="86g7n8g67nm,8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm 8m787mg8"`
- `data-isso-page-author-hashes="86g7n8g67nm, 8m787mg8"`
This is parsed using [code from this article](https://www.tutorialspoint.com/split-space-delimited-string-and-trim-extra-commas-and-spaces-in-javascript).
## Screenshot with the theming shown in docs:
![Screenshot 2022-05-07 at 14-20-11 Isso Demo](https://user-images.githubusercontent.com/17971474/167268827-32b47799-e262-48b6-b19a-1054e14ec8bb.png)
```css
.isso-comment.isso-is-page-author > .isso-text-wrapper {
background-color: #bae0ea;
}
.isso-comment.isso-is-page-author > .isso-text-wrapper > .isso-comment-header > .isso-author {
color: #19798d;
}
``` | null | 2022-04-24 00:11:06+00:00 | 2022-05-07 20:19:33+00:00 | isso/js/app/templates/comment.js | var html = function (globals) {
var i18n = globals.i18n;
var comment = globals.comment;
var conf = globals.conf;
var datetime = globals.datetime;
var humanize = globals.humanize;
var svg = globals.svg;
var author = comment.author ? comment.author : i18n('comment-anonymous');
return "" +
"<div class='isso-comment' id='isso-" + comment.id + "'>"
+ (conf.gravatar ? "<div class='isso-avatar'><img src='" + comment.gravatar_image + "'></div>" : '')
+ (conf.avatar ? "<div class='isso-avatar'><svg data-hash='" + comment.hash + "'</svg></div>" : '')
+ "<div class='isso-text-wrapper'>"
+ "<div class='isso-comment-header' role='meta'>"
+ (comment.website
? "<a class='isso-author' href='" + comment.website + "' rel='nofollow'>" + author + "</a>"
: "<span class='isso-author'>" + author + "</span>")
+ "<span class='isso-spacer'>•</span>"
+ "<a class='isso-permalink' href='#isso-" + comment.id + "'>"
+ "<time title='" + humanize(comment.created) + "' datetime='" + datetime(comment.created) + "'>" + humanize(comment.created) + "</time>"
+ "</a>"
+ "<span class='isso-note'>"
+ (comment.mode == 2 ? i18n('comment-queued') : (comment.mode == 4 ? i18n('comment-deleted') : ''))
+ "</span>"
+ "</div>" // .text-wrapper
+ "<div class='isso-text'>"
+ (comment.mode == 4 ? '<p> </p>' : comment.text)
+ "</div>" // .text
+ "<div class='isso-comment-footer'>"
+ (conf.vote
? "<a class='isso-upvote' href='#'>" + svg['arrow-up'] + "</a>"
+ "<span class='isso-spacer'>|</span>"
+ "<a class='isso-downvote' href='#'>" + svg['arrow-down'] + "</a>"
: '')
+ "<a class='isso-reply' href='#'>" + i18n('comment-reply') + "</a>"
+ "<a class='isso-edit' href='#'>" + i18n('comment-edit') + "</a>"
+ "<a class='isso-delete' href='#'>" + i18n('comment-delete') + "</a>"
+ "</div>" // .isso-comment-footer
+ "<div class='isso-follow-up'></div>"
+ "</div>" // .text-wrapper
+ "</div>" // .isso-comment
};
module.exports = html;
| var html = function (globals) {
var i18n = globals.i18n;
var comment = globals.comment;
var conf = globals.conf;
var datetime = globals.datetime;
var humanize = globals.humanize;
var svg = globals.svg;
var author = comment.author ? comment.author : i18n('comment-anonymous');
var isPageAuthor = conf["page-author-hashes"].indexOf(comment.hash) > -1;
var pageAuthorClass = (isPageAuthor ? " isso-is-page-author" : '');
return "" +
"<div class='isso-comment" + pageAuthorClass + "' id='isso-" + comment.id + "' data-hash='" + comment.hash + "'>"
+ (conf.gravatar ? "<div class='isso-avatar'><img src='" + comment.gravatar_image + "'></div>" : '')
+ (conf.avatar ? "<div class='isso-avatar'><svg data-hash='" + comment.hash + "'</svg></div>" : '')
+ "<div class='isso-text-wrapper'>"
+ "<div class='isso-comment-header' role='meta'>"
+ (comment.website
? "<a class='isso-author' href='" + comment.website + "' rel='nofollow'>" + author + "</a>"
: "<span class='isso-author'>" + author + "</span>")
+ (isPageAuthor
? "<span class='isso-spacer'>•</span>"
+ "<span class='isso-page-author-suffix'>" + i18n('comment-page-author-suffix') + "</span>"
: '' )
+ "<span class='isso-spacer'>•</span>"
+ "<a class='isso-permalink' href='#isso-" + comment.id + "'>"
+ "<time title='" + humanize(comment.created) + "' datetime='" + datetime(comment.created) + "'>" + humanize(comment.created) + "</time>"
+ "</a>"
+ "<span class='isso-note'>"
+ (comment.mode == 2 ? i18n('comment-queued') : (comment.mode == 4 ? i18n('comment-deleted') : ''))
+ "</span>"
+ "</div>" // .text-wrapper
+ "<div class='isso-text'>"
+ (comment.mode == 4 ? '<p> </p>' : comment.text)
+ "</div>" // .text
+ "<div class='isso-comment-footer'>"
+ (conf.vote
? "<a class='isso-upvote' href='#'>" + svg['arrow-up'] + "</a>"
+ "<span class='isso-spacer'>|</span>"
+ "<a class='isso-downvote' href='#'>" + svg['arrow-down'] + "</a>"
: '')
+ "<a class='isso-reply' href='#'>" + i18n('comment-reply') + "</a>"
+ "<a class='isso-edit' href='#'>" + i18n('comment-edit') + "</a>"
+ "<a class='isso-delete' href='#'>" + i18n('comment-delete') + "</a>"
+ "</div>" // .isso-comment-footer
+ "</div>" // .text-wrapper
+ "<div class='isso-follow-up'></div>"
+ "</div>" // .isso-comment
};
module.exports = html;
| BBaoVanC | 05ba6023da7337340208c16e1108318195ceb5d4 | 0c8673561e2f8de129c5d82fba7e22de7d1a4043 | This is Farsi with a Farsi name ("Farid"-> "فرید"): `فرید•نویسنده•17 دقیقه پیش`
This is Farsi with a Latin-script name ("John"): `John•نویسنده•17 دقیقه پیش`
"Author" ("نویسنده") will confusingly be placed at the rightmost edge if the Author name is Latin-script. "نویسنده" highlighted in red for this screenshot:
![Screenshot from 2022-05-07 19-24-05](https://user-images.githubusercontent.com/10212877/167265264-a3cf93ac-f947-4fd3-b52a-cf3981eef3a0.png)
Not all that important for this PR, we'd probably be better off with proper RTL support by dynamically setting `direction: rtl` for all of `#isso-thread` if detected/set language is an RTL one. | ix5 | 52 |
posativ/isso | 832 | treewide: Support and test against Python 3.11 | null | null | 2022-03-28 08:22:33+00:00 | 2022-11-03 14:39:50+00:00 | CHANGES.rst | Changelog for Isso
==================
%(version)s (%(date)s)
----------------------
New Features
^^^^^^^^^^^^
- notifications: Implement 'List-Unsubscribe' header (`#906`_, ix5)
- css: Grey styling for comment code, code blocks (`#907`_, ix5)
.. _#906: https://github.com/posativ/isso/pull/906
.. _#907: https://github.com/posativ/isso/pull/907
Breaking Changes
^^^^^^^^^^^^^^^^
- TBD
Bugfixes & Improvements
^^^^^^^^^^^^^^^^^^^^^^^
- TBD
0.13.0 (2022-06-12)
-------------------
New Features
^^^^^^^^^^^^
- Add ``data-isso-reply-notifications-default-enabled`` option to configure
whether or not the subscribe to replies checkbox should be checked by default.
(`#846`_, BBaoVanC)
- Accessibility: Use labels rather than placeholders for name, email & website
in post box (`#861`_, ix5)
- Add ``data-isso-page-author-hashes`` option to client which makes it possible
to style comments and replies made by the page's author(s).
- Add Ukrainian localisation (`#878`_, okawo80085)
- Enable Turkish localisation (`#879`_)
Breaking Changes
^^^^^^^^^^^^^^^^
- css, js: Prefix all classes with ``isso-`` (`#816`_, ix5)
Now Isso's CSS is "namespaced" in order not to conflict with other classes on
the page.
This change necessitates adjusting custom CSS files to the new names.
- Drop support for outdated Python version 3.5 (`#808`_, l33tname)
- Strip trailing slash from ``public-endpoint``. A trailing slash in ``[server]
public-endpoint`` is now discouraged and throws a warning (`#876`_, ix5)
Bugfixes & Improvements
^^^^^^^^^^^^^^^^^^^^^^^
- Replace ``contenteditable`` ``div`` with ``textarea`` to fix issues when
editing messages that contain indented code (`#887`_, BBaoVanC)
- Fix avatar sizing, limit default gravatar images to 55px (`#831`_, l33tname)
In case of a custom gravatar URL, the ``&s=55`` size parameter will have
to be added, see `Gravatar - Image requests`_.
- Re-enable ``no-intra-emphasis`` misaka extension in default config (`#865`_, ix5)
- Allow ``sup`` and ``sub`` HTML elements by default (`#865`_, ix5)
- Move ``isso-dev.cfg`` to ``contrib/`` folder (`#882`_, ix5)
- Drop ``Flask-Caching`` dependency and use drop-in solution instead (`#893`_, ix5)
- Run automated screenshot comparisons for testing (`#889`_, ix5)
- wsgi: Return HTTP errors as JSON if client prefers it (`#488`_, sundbry)
- Verify that parent of new comment is in same thread (`#885`_, ix5)
- When importing from WordPress single newlines are now converted to line breaks
(`#903`_, projectgus)
- **API:**
- Add ``/config`` endpoint for fetching server configuration options that
affect the client (`#880`_, ix5)
- Remove ``/count`` GET endpoint (use POST instead) (`#883`_, ix5)
.. _Gravatar - Image requests: http://en.gravatar.com/site/implement/images/
.. _#488: https://github.com/posativ/isso/pull/488
.. _#808: https://github.com/posativ/isso/pull/808
.. _#816: https://github.com/posativ/isso/pull/816
.. _#831: https://github.com/posativ/isso/pull/831
.. _#846: https://github.com/posativ/isso/pull/846
.. _#861: https://github.com/posativ/isso/pull/861
.. _#865: https://github.com/posativ/isso/pull/865
.. _#876: https://github.com/posativ/isso/pull/876
.. _#878: https://github.com/posativ/isso/pull/878
.. _#879: https://github.com/posativ/isso/pull/879
.. _#880: https://github.com/posativ/isso/pull/880
.. _#882: https://github.com/posativ/isso/pull/882
.. _#883: https://github.com/posativ/isso/pull/883
.. _#885: https://github.com/posativ/isso/pull/885
.. _#887: https://github.com/posativ/isso/pull/887
.. _#889: https://github.com/posativ/isso/pull/889
.. _#893: https://github.com/posativ/isso/pull/893
.. _#903: https://github.com/posativ/isso/pull/903
0.13.0.beta1 (2022-06-05)
-------------------------
New Features
^^^^^^^^^^^^
- Add ``data-isso-reply-notifications-default-enabled`` option to configure
whether or not the subscribe to replies checkbox should be checked by default.
(`#846`_, BBaoVanC)
- Accessibility: Use labels rather than placeholders for name, email & website
in post box (`#861`_, ix5)
- Add ``data-isso-page-author-hashes`` option to client which makes it possible
to style comments and replies made by the page's author(s).
- Add Ukrainian localisation (`#878`_, okawo80085)
- Enable Turkish localisation (`#879`_)
Breaking Changes
^^^^^^^^^^^^^^^^
- css, js: Prefix all classes with ``isso-`` (`#816`_, ix5)
Now Isso's CSS is "namespaced" in order not to conflict with other classes on
the page.
This change necessitates adjusting custom CSS files to the new names.
- Drop support for outdated Python version 3.5 (`#808`_, l33tname)
- Strip trailing slash from ``public-endpoint``. A trailing slash in ``[server]
public-endpoint`` is now discouraged and throws a warning (`#876`_, ix5)
Bugfixes & Improvements
^^^^^^^^^^^^^^^^^^^^^^^
- Replace ``contenteditable`` ``div`` with ``textarea`` to fix issues when
editing messages that contain indented code (`#887`_, BBaoVanC)
- Fix avatar sizing, limit default gravatar images to 55px (`#831`_, l33tname)
In case of a custom gravatar URL, the ``&s=55`` size parameter will have
to be added, see `Gravatar - Image requests`_.
- Re-enable ``no-intra-emphasis`` misaka extension in default config (`#865`_, ix5)
- Allow ``sup`` and ``sub`` HTML elements by default (`#865`_, ix5)
- Move ``isso-dev.cfg`` to ``contrib/`` folder (`#882`_, ix5)
- Drop ``Flask-Caching`` dependency and use drop-in solution instead (`#893`_, ix5)
- Run automated screenshot comparisons for testing (`#889`_, ix5)
- wsgi: Return HTTP errors as JSON if client prefers it (`#488`_, sundbry)
- Verify that parent of new comment is in same thread (`#885`_, ix5)
- **API:**
- Add ``/config`` endpoint for fetching server configuration options that
affect the client (`#880`_, ix5)
- Remove ``/count`` GET endpoint (use POST instead) (`#883`_, ix5)
.. _Gravatar - Image requests: http://en.gravatar.com/site/implement/images/
.. _#488: https://github.com/posativ/isso/pull/488
.. _#808: https://github.com/posativ/isso/pull/808
.. _#816: https://github.com/posativ/isso/pull/816
.. _#831: https://github.com/posativ/isso/pull/831
.. _#846: https://github.com/posativ/isso/pull/846
.. _#861: https://github.com/posativ/isso/pull/861
.. _#865: https://github.com/posativ/isso/pull/865
.. _#876: https://github.com/posativ/isso/pull/876
.. _#878: https://github.com/posativ/isso/pull/878
.. _#879: https://github.com/posativ/isso/pull/879
.. _#880: https://github.com/posativ/isso/pull/880
.. _#882: https://github.com/posativ/isso/pull/882
.. _#883: https://github.com/posativ/isso/pull/883
.. _#885: https://github.com/posativ/isso/pull/885
.. _#887: https://github.com/posativ/isso/pull/887
.. _#889: https://github.com/posativ/isso/pull/889
.. _#893: https://github.com/posativ/isso/pull/893
0.12.6 (2022-03-06)
-------------------
- Serve isso.css separately to avoid ``style-src: unsafe-inline`` CSP and allow
clients to override fetch location (#704, ix5):
data-isso-css-url="https://comments.example.org/css/isso.css"
- New "samesite" option in [server] section to override SameSite header for
cookies. (#700, ix5)
- Fallback for SameSite header depending on whether host is served over https
or http (#700, ix5)
- Have client read out shared settings from server. (#311, pellenilsson)
This affects these settings for which ``data-isso-*`` values will be ignored:
[general]
reply-notifications
gravatar
[guard]
reply-to-self
require-author
require-email
- Improved detection of browser-supplied language preferences (#521)
Isso will now honor the newer ``navigator.languages`` global property
as well as ``navigator.language`` and ``navigator.userLanguage``.
There is a new configuration property ``data-isso-default-lang``
that specifies the language to use (instead of English) when none
of these is available. (The existing ``data-isso-lang`` *overrides*
browser-supplied language preferences.)
- Remove ``ISSO_CORS_ORIGIN`` environ variable, which never worked at all
(#803, ix5)
0.12.5 (2021-03-09)
-------------------
- Don't ignore missing configuration files.
(Jelmer Vernooij)
0.12.4 (2021-02-03)
-------------------
- Require Python >= 3.5, for consistency with werkzeug.
(#698, Stefan Gehn)
- Use npm for package installation.
(#695, Stefan Gehn)
- Use sassc. (Stefan Gehn)
- Cope with broken HTTP clients that require specific casing of
"200 OK". (#646, #347, Konzertheld)
- Add European Portuguese translation. (#692, boturon)
- Various doc updates. (ix5)
- Add Turkish translation. (Özcan Oğuz, #669)
- Drop Python 2 support. (Jelmer Vernooij)
0.12.3 (2020-02-22)
-------------------
- New "flags" option in the [markdown] section to customize Misaka's Markdown
HTML rendering. By default, no flags are set.
[markup]
flags = skip-html, escape, hard-wrap
Check docs/configuration/server.rst for more details. #616
* Fix compatibility with newer versions of werkzeug. #614
* Add Python 3.8 support. #600, #615
* New 'latest' endpoint to serve latest comments. #556
* include admin.js in Python Package. #606
* Add a approve-if-email-previously-approved setting.
* Fall back to author names in gravatars (#482)
* Make Isso compatible with Content Security Policies without `script-src 'unsafe-inline'`. #597
* Set subject for notification about new comment, subject should not be empty. #589
* Fix rendering of disabled.html for 'Sub URI' sites.
* contrib: Add Blogger importer tool. #529
* Return 200 with empty array when there are no comments. #301
* Translation updates for Polish, Slovak, Occitan.
* Redirect to comment after moderation. #358
0.12.2 (2019-01-21)
-------------------
- Revert use of labels instead of placeholders, since it breaks
mail notifications. #524
0.12.1 (2019-01-19)
-------------------
- Revert fix for duplicate slashes, as it prevents isso from
starting in some cases. #523
0.12.0 (2019-01-18)
-------------------
- Fix compatibility with new XML API.
- Don't enable admin interface with default password by default. #491
- Add support and documentation for "generic" imports.
- Remove potential duplicate slashes in URLs from
email links. #420
- Add data-isso-reply-notifications to attributes in configuration.
- Use default IP in imports if none is found. Fixes imports of some comments.
- embed: fix feed link creation on older browsers.
- Properly handle to field in mail notifications when using uWSGI spooler
- css: fix vertical alignment of notification checkbox
0.11.1 (2018-11-03)
-------------------
- Include pre-built minified JavaScript and CSS.
0.11.0 (2018-11-03)
-------------------
Bugs & features:
- Fix link in moderation mails if isso is setup on a sub-url (e.g. domain.tld/comments/)
- Add reply notifications
- Add admin interface
- Add links highlighting in comments
- Add apidoc
- Add rc.d script for FreeBSD
- Add the possibility to set CORS Origin through ISSO_CORS_ORIGIN environ variable
- Add preview button
- Add Atom feed at /feed?uri={thread-id}
- Add optionnal gravatar support
- Add nofollow noopener on links inside comments
- Add Dockerfile
- Upgraded to Misaka 2
- Some tests/travis/documentation improvements and fixes + pep8
Translations:
- Fix Chinese translation & typo in CJK
- Add Danish translation
- Add Hungarian translation
- Add Persian translation
- Improvement on german translation
0.10.6 (2016-09-22)
-------------------
- fix missing configuration field
0.10.5 (2016-09-20)
-------------------
- add support for different vote levels, #260
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg.
`"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given
one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg.
put a star on popular comments).
- add new post preview API endpoint, #254
- add an option for mandatory author, #257
- clients can now use `data-title` to get the HTML title for a new page, #252
- add finish translation and other minor bugfixes
0.10.4 (2016-04-12)
-------------------
- fix wrapper attribute when using data-isso-require-mail="true", #238
- fix reponse for OPTIONS response on Python 3, #242
0.10.3 (2016-02-24)
-------------------
- follow redirects, #193
0.10.2 (2016-02-21)
-------------------
- fix getAttribute return value
0.10.1 (2016-02-06)
-------------------
- fix empty author, email and website values when writing a comment
0.10 (2016-02-06)
-----------------
- add new configuration section for hash handling.
[hash]
salt = Eech7co8Ohloopo9Ol6baimi
algorithm = pbkdf2
You can customize the salt, choose different hash functions and tweak the
parameters for PBKDF2.
- Python 3.4+ validate TLS connections against the system's CA. Previously no
validation was in place, see PEP-446__ for details.
- add `fenced_code` and `no_intra_emphasis` to default configuration.
Fenced code allows to write code without indentation using `~~~` delimiters
(optionally with language identifier).
Intra emphasis would compile `foo_bar_baz` to foo<em>bar</em>baz. This
behavior is very confusing for users not knowing the Markdown spec in detail.
- new configuration to require an email when submitting comments, #199. Set
[guard]
require-email = true
and use `data-isso-require-email="true"` to enable this feature. Disabled by
default.
- new Bulgarian translation by sahwar, new Swedish translation by Gustav
Näslund – #143, new Vietnamese translation by Đinh Xuân Sâm, new Croatian
translation by streger, new Czech translation by Jan Chren
- fix SMTP setup without credentials, #174
- version pin Misaka to 1.x, html5lib to 0.9999999
.. __: https://www.python.org/dev/peps/pep-0466/
0.9.10 (2015-04-11)
-------------------
- fix regression in SMTP authentication, #174
0.9.9 (2015-03-04)
------------------
- several Python 3.x related bugfixes
- don't lose comment form if the server rejected the POST request, #144
- add localStorage fallback if QUOTA_EXCEEDED_ERR is thrown (e.g. Safari
private browsing)
- add '--empty-id' flag to Disqus import, because Disqus' export sucks
- (re)gain compatibility with Werkzeug 0.8 and really old html5lib versions
available in Debian Squeeze, #170 & #168
- add User-Agent when Isso requests the URL, an alternate way to #151 (add
'X-Isso' when requesting).
0.9.8 (2014-10-08)
------------------
- add compatibility with configparser==3.5.0b1, #128
0.9.7 (2014-09-25)
------------------
- fix SMTP authentication using CRAM-MD5 (incorrect usage of
`smtplib`), #126
0.9.6 (2014-08-18)
------------------
- remember name, email and website in localStorage, #119
- add option to hide voting feature, #115
data-isso-vote="true|false"
- remove email field from JSON responses
This is a quite serious issue. For the identicon, an expensive hash is used
to avoid the leakage of personal information like a real email address. A
`git blame` reveals, the email has been unintentionally exposed since the very
first release of Isso :-/
The testsuite now contains a dedicated test to prevent this error in the
future.
0.9.5 (2014-08-10)
------------------
- prevent no-break space ( ) insertion to enable manual line breaks using
two trailing spaces (as per Markdown convention), #112
- limit request size to 256 kb, #107
Previously unlimited or limited by proxy server). 256 kb is a rough
approximation of the next database schema with comments limited to 65535
characters and additional fields.
- add support for logging to file, #103
[general]
log-file =
- show timestamp when hovering <time>, #104
- fix a regression when editing comments with multiple paragraphs introduced
in 0.9.3 which would HTML escape manually inserted linebreaks.
0.9.4 (2014-07-09)
------------------
- fixed a regression when using Isso and Gevent
0.9.3 (2014-07-09)
------------------
- remove scrollIntoView while expanding further comments if a fragment is used
(e.g. #isso-thread brought you back to the top, unexpectedly)
- implement a custom Markdown renderer to support multi-line code listings. The
extension "fenced_code" is now enabled by default and generates HTML
compatible with Highlight.js__.
- escape HTML entities when editing a comment with raw HTML
- fix CSS for input
- remove isso.css from binary distribution to avoid confusion (it's still there
from the very first release, but modifications do not work)
.. __: http://highlightjs.org/
0.9 (2014-05-29)
----------------
- comment pagination by Srijan Choudhary, #15
Isso can now limit the amount of comments shown by default and add link to
show more. By default, all top-level comments are shown but only 5 nested
comments (per reply). You can override the settings:
isso-data-max-comments-top="N"
isso-data-max-comments-nested="N"
Where N is a number from 0 to infinity ("inf"). If you limit the amount of
shown top level comments, the overall comment count may be incorrect and a
known issue.
You can also configure the amount of comments shown per click (5 by default):
isso-data-reveal-on-click="N"
This feature also required a change in the comment structure. Previously, all
comments are stored tree-like but shown linearly. To ease the implementation
of pagination, the comment tree is now limited to a maximum depth of one.
Jeff Atwood explains, why `discussions are flat by design`__.
.. __: http://blog.codinghorror.com/web-discussions-flat-by-design/
When you upgrade, Isso will automatically normalize the tree and some
information gets lost. All new replies to a comment are now automatically a
direct child of the top-level comment.
- style improvements by William Dorffer, #39, #84 #90 and #91
Isso now longer uses a fat SCSS library, but plain CSS instead. The design is
now responsive and no longer sets global CSS rules.
- experimental WordPress import, #75
Isso should be able to import WXR 1.0-1.2 exports. The import code is based
on two WXR dumps I found (and created) and may not work for you. Please
report any failure.
- avatar changes, #49
You can now configure the client to not show avatars:
data-isso-avatar="false"
Also there is no longer an avatar shown next to the comment box. This is due
to the new CSS and removes two runtime dependencies.
- you may now set a full From header, #87
[smtp]
from = Foo Bar <spam@local>
- SMTP (all caps) is now recognized for notifications, #95
- Isso now ships a small demo site at /demo, #44
- a few bugfixes: Disqus import now anonymizes IP addresses, uWSGI spooling for
Python 3, HTTP-Referer fallback for HTTP-Origin
- remove Django's PBKDF2 implementation in favour of the PBKDF2 function
available in werkzeug 0.9 or higher. If you're still using werkzeug 0.8, Isso
imports passlib__ as fallback (if available).
This release also features a new templating engine Jade__ which replaces
Markup.js__. Jade can compile directly to JavaScript with a tiny runtime module
on the client. Along with the removal of sha1.js and pbkdf2.js and a few build
optimizations, the JS client now weighs only 40kb (12kb gzipped) – 52kb resp.
17kb before.
.. __: https://pypi.python.org/pypi/passlib
.. __: http://jade-lang.com/
.. __: https://github.com/adammark/Markup.js
0.8 (2014-03-28)
----------------
- replace ``<textarea>`` with ``<div contentedtiable="true">`` to remove the
sluggish auto-resize on input feature. If you use a custom CSS, replace
``textarea`` with ``.textarea`` and also set ``white-space: pre``.
- remove superscript extension from Markdown defaults as it may lead to
unexpected behavior for certain smileys such as "^^". To enable the extension,
add
[markup]
options = superscript
allowed-elements = sup
to your configuration.
- comment count requests are now bundled into a single POST request, but the old
API is still there (deprecated though).
- store *session-key* in database (once generated on database creation). That
means links to activate, edit or delete comments are now always valid even
when you restart Isso.
Currently statically set session keys in ``[general]`` are automatically
migrated into the database on startup and you will get a notice that you can
remove this option.
- fix undefined timestamp when client time differs for more than 1 second.
The human-readable "time ago" deltas have been refined to match `Moment.js`_
behavior.
- avatar colors and background can now be customized:
* ``data-isso-avatar-bg="#f0f0f0"`` sets the background color
* ``data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."`` sets possible
avatar colors (up to 8 colors are possible).
- new [markup] section to customize Misaka's Markdown generation (strikethrough,
superscript and autolink enabled by default). Furthermore, you can now allow
certain HTML elemenets and attributes in the generated output, e.g. to enable
images, set
[markup]
allowed-elements = img
allowed-attributes = src
Check docs/configuration/server.rst for more details.
- replace requirejs-domready with a (self-made) HTML5 idiom, #51
.. _Moment.js: http://momentjs.com/docs/#/displaying/fromnow/
0.7 (2014-01-29)
----------------
- fix malicious HTML injection (due to wrong API usage). All unknown/unsafe
HTML tags are now removed from the output (`html5lib` 0.99(9) or later) or
properly escaped (older `html5lib` versions).
See 36d702c and 3a1f92b for more details.
- remove kriskowal/q JS library (promises implementation) in favour of a
self-made 50 LoC implementation to ease packaging (for Debian), #51
- add documentation to display a comment counter, #56 and #57
- SMTP notifications now support STARTTLS and use this transport security
by default, #48 and #58. This also changes the configuration option from
`ssl = [yes|no]` to `security = [none|starttls|ssl]`.
- translation can now be made (and updated) with Transifex_. If you want to
take ownership for a language, contact me on IRC.
- fix french pluralform
- the (by default random) session-key is now shown on application startup
to make different keys per startup more visible
- use `threading.lock` by default for systems without semaphore support
.. _Transifex: https://www.transifex.com/projects/p/isso/
0.6 (2013-12-16)
----------------
Major improvements:
- override thread discovery with data-isso-id="...", #27
To use the same thread for different URLs, you can now add a custom
``data-isso-id="my-id"`` attribute which is used to identify and retrieve
comments (defaults to current URL aka `window.location.pathname`).
- `isso.dispatch` now dispatches multiple websites (= configurations) based on
URL prefixes
- fix a cross-site request forgery vulnerability for comment creation, voting,
editing and deletion, #40
- show modal dialog to confirm comment deletion and activation, #36
- new, comprehensive documentation based on reST + Sphinx:
http://posativ.org/docs (or docs/ in the repository). Also includes an
annotated `example.conf`, #43
- new italian and russian translations
Minor improvements:
- move `isso:application` to `isso.run:application` to avoid uneccessary
initialization in some cases (change module if you use uWSGI or Gunicorn)
- add Date header to email notifications, #42
- check for blank text in new comment, #41
- work around IE10's HTML5 abilities for custom data-attributes
- add support for Gunicorn (and other pre-forking WSGI servers)
0.5 (2013-11-17)
----------------
Major improvements:
- `listen` option replaces `host` and `port` to support UNIX domain sockets, #25
Instead of `host = localhost` and `port = 8080`, use
`listen = http://localhost:8080`. To listen on a UNIX domain socket, replace
`http://` with `unix://`, e.g. `unix:///tmp/isso.sock`.
- new option `notify` (in the general section) is used to choose (one or more)
notification backends (currently only SMTP is available, though). Isso will
no longer automatically use SMTP for notifications if the initial connection
succeeds.
- new options to control the client integration
* ``data-isso-css="false"`` prevents the client from appending the CSS to the
document. Enabled by default.
* ``data-isso-lang="de"`` overrides the useragent's preferred language (de, en
and fr are currently supported).
* ``data-isso-reply-to-self="true"`` should be set, when you allow reply to
own comments (see server configuration for details).
- add support for `gevent <http://www.gevent.org/>`_, a coroutine-based Python
networking library that uses greenlets (lightweight threads). Recommended
WSGI server when not running with uWSGI (unfortunately stable gevent is not
yet able to listen on a UNIX domain socket).
- fix a serious issue with the voters bloomfilter. During an Isso run, the
ip addresses from all commenters accumulated into the voters bloomfilter
for new comments. Thus, previous commenters could no longer vote other
comments. This fixes the rare occurences of #5.
In addition to this fix, the current voters bloomfilter will be re-initialized
if you are using Isso 0.4 or below (this is not necessary, but on the
other hand, the current bloomfilter for each comment is sort-of useless).
- french translation (thanks to @sploinga), #38
- support for multiple sites, part of #34
Minor improvements:
- `ipaddr` is now used as `ipaddress` fallback for Python 2.6 and 2.7, #32
- changed URL to activate and delete comments to `/id/<N:int>/activate` etc.
- import command uses `<link>` tag instead of `<id>` to extract the relative
URL path, #37
- import command now uses `isDeleted` to mark comments as deleted (and
eventually remove stale comments). This seems to affect only a few comments
from a previous WordPress import into Disqus.
- import command lists orphaned comments after import.
- import command now has a ``--dry-run`` option to do no actual operation on
the database.
0.4 (2013-11-05)
----------------
- Isso now handles cross-domain requests and cookies, fixes #24
- Isso for Python 2.x now supports werkzeug>=0.8
- limit email length to 254 to avoid Hash-DDoS
- override Isso API location with ``data-isso="..."`` in the script tag
- override HTML title parsing with a custom ``data-title="..."`` attribute
in ``<div id="isso-thread"></div>``
0.3 (2013-11-01)
----------------
- improve initial comment loading performance in the client
- cache slow REST requests, see #18
- add a SQLite trigger that detects and removes stale threads (= threads,
with all comments being removed) from the database when a comment is
removed.
- PyPi releases now include an uncompressed version of the JavaScript
files -- `embed.dev.js` and `count.dev.js` -- to track down errors.
- use uWSGI's internal locking instead of a self-made shared memory lock
0.2 (2013-10-29)
----------------
- initial PyPi release
| Changelog for Isso
==================
%(version)s (%(date)s)
----------------------
New Features
^^^^^^^^^^^^
- notifications: Implement 'List-Unsubscribe' header (`#906`_, ix5)
- css: Grey styling for comment code, code blocks (`#907`_, ix5)
.. _#906: https://github.com/posativ/isso/pull/906
.. _#907: https://github.com/posativ/isso/pull/907
Breaking Changes
^^^^^^^^^^^^^^^^
- TBD
Bugfixes & Improvements
^^^^^^^^^^^^^^^^^^^^^^^
- Python 3.11 support (`#832`_, l33tname)
0.13.0 (2022-06-12)
-------------------
New Features
^^^^^^^^^^^^
- Add ``data-isso-reply-notifications-default-enabled`` option to configure
whether or not the subscribe to replies checkbox should be checked by default.
(`#846`_, BBaoVanC)
- Accessibility: Use labels rather than placeholders for name, email & website
in post box (`#861`_, ix5)
- Add ``data-isso-page-author-hashes`` option to client which makes it possible
to style comments and replies made by the page's author(s).
- Add Ukrainian localisation (`#878`_, okawo80085)
- Enable Turkish localisation (`#879`_)
Breaking Changes
^^^^^^^^^^^^^^^^
- css, js: Prefix all classes with ``isso-`` (`#816`_, ix5)
Now Isso's CSS is "namespaced" in order not to conflict with other classes on
the page.
This change necessitates adjusting custom CSS files to the new names.
- Drop support for outdated Python version 3.5 (`#808`_, l33tname)
- Strip trailing slash from ``public-endpoint``. A trailing slash in ``[server]
public-endpoint`` is now discouraged and throws a warning (`#876`_, ix5)
Bugfixes & Improvements
^^^^^^^^^^^^^^^^^^^^^^^
- Replace ``contenteditable`` ``div`` with ``textarea`` to fix issues when
editing messages that contain indented code (`#887`_, BBaoVanC)
- Fix avatar sizing, limit default gravatar images to 55px (`#831`_, l33tname)
In case of a custom gravatar URL, the ``&s=55`` size parameter will have
to be added, see `Gravatar - Image requests`_.
- Re-enable ``no-intra-emphasis`` misaka extension in default config (`#865`_, ix5)
- Allow ``sup`` and ``sub`` HTML elements by default (`#865`_, ix5)
- Move ``isso-dev.cfg`` to ``contrib/`` folder (`#882`_, ix5)
- Drop ``Flask-Caching`` dependency and use drop-in solution instead (`#893`_, ix5)
- Run automated screenshot comparisons for testing (`#889`_, ix5)
- wsgi: Return HTTP errors as JSON if client prefers it (`#488`_, sundbry)
- Verify that parent of new comment is in same thread (`#885`_, ix5)
- When importing from WordPress single newlines are now converted to line breaks
(`#903`_, projectgus)
- **API:**
- Add ``/config`` endpoint for fetching server configuration options that
affect the client (`#880`_, ix5)
- Remove ``/count`` GET endpoint (use POST instead) (`#883`_, ix5)
.. _Gravatar - Image requests: http://en.gravatar.com/site/implement/images/
.. _#488: https://github.com/posativ/isso/pull/488
.. _#808: https://github.com/posativ/isso/pull/808
.. _#816: https://github.com/posativ/isso/pull/816
.. _#831: https://github.com/posativ/isso/pull/831
.. _#846: https://github.com/posativ/isso/pull/846
.. _#861: https://github.com/posativ/isso/pull/861
.. _#865: https://github.com/posativ/isso/pull/865
.. _#876: https://github.com/posativ/isso/pull/876
.. _#878: https://github.com/posativ/isso/pull/878
.. _#879: https://github.com/posativ/isso/pull/879
.. _#880: https://github.com/posativ/isso/pull/880
.. _#882: https://github.com/posativ/isso/pull/882
.. _#883: https://github.com/posativ/isso/pull/883
.. _#885: https://github.com/posativ/isso/pull/885
.. _#887: https://github.com/posativ/isso/pull/887
.. _#889: https://github.com/posativ/isso/pull/889
.. _#893: https://github.com/posativ/isso/pull/893
.. _#903: https://github.com/posativ/isso/pull/903
0.13.0.beta1 (2022-06-05)
-------------------------
New Features
^^^^^^^^^^^^
- Add ``data-isso-reply-notifications-default-enabled`` option to configure
whether or not the subscribe to replies checkbox should be checked by default.
(`#846`_, BBaoVanC)
- Accessibility: Use labels rather than placeholders for name, email & website
in post box (`#861`_, ix5)
- Add ``data-isso-page-author-hashes`` option to client which makes it possible
to style comments and replies made by the page's author(s).
- Add Ukrainian localisation (`#878`_, okawo80085)
- Enable Turkish localisation (`#879`_)
Breaking Changes
^^^^^^^^^^^^^^^^
- css, js: Prefix all classes with ``isso-`` (`#816`_, ix5)
Now Isso's CSS is "namespaced" in order not to conflict with other classes on
the page.
This change necessitates adjusting custom CSS files to the new names.
- Drop support for outdated Python version 3.5 (`#808`_, l33tname)
- Strip trailing slash from ``public-endpoint``. A trailing slash in ``[server]
public-endpoint`` is now discouraged and throws a warning (`#876`_, ix5)
Bugfixes & Improvements
^^^^^^^^^^^^^^^^^^^^^^^
- Replace ``contenteditable`` ``div`` with ``textarea`` to fix issues when
editing messages that contain indented code (`#887`_, BBaoVanC)
- Fix avatar sizing, limit default gravatar images to 55px (`#831`_, l33tname)
In case of a custom gravatar URL, the ``&s=55`` size parameter will have
to be added, see `Gravatar - Image requests`_.
- Re-enable ``no-intra-emphasis`` misaka extension in default config (`#865`_, ix5)
- Allow ``sup`` and ``sub`` HTML elements by default (`#865`_, ix5)
- Move ``isso-dev.cfg`` to ``contrib/`` folder (`#882`_, ix5)
- Drop ``Flask-Caching`` dependency and use drop-in solution instead (`#893`_, ix5)
- Run automated screenshot comparisons for testing (`#889`_, ix5)
- wsgi: Return HTTP errors as JSON if client prefers it (`#488`_, sundbry)
- Verify that parent of new comment is in same thread (`#885`_, ix5)
- **API:**
- Add ``/config`` endpoint for fetching server configuration options that
affect the client (`#880`_, ix5)
- Remove ``/count`` GET endpoint (use POST instead) (`#883`_, ix5)
.. _Gravatar - Image requests: http://en.gravatar.com/site/implement/images/
.. _#488: https://github.com/posativ/isso/pull/488
.. _#808: https://github.com/posativ/isso/pull/808
.. _#816: https://github.com/posativ/isso/pull/816
.. _#831: https://github.com/posativ/isso/pull/831
.. _#846: https://github.com/posativ/isso/pull/846
.. _#861: https://github.com/posativ/isso/pull/861
.. _#865: https://github.com/posativ/isso/pull/865
.. _#876: https://github.com/posativ/isso/pull/876
.. _#878: https://github.com/posativ/isso/pull/878
.. _#879: https://github.com/posativ/isso/pull/879
.. _#880: https://github.com/posativ/isso/pull/880
.. _#882: https://github.com/posativ/isso/pull/882
.. _#883: https://github.com/posativ/isso/pull/883
.. _#885: https://github.com/posativ/isso/pull/885
.. _#887: https://github.com/posativ/isso/pull/887
.. _#889: https://github.com/posativ/isso/pull/889
.. _#893: https://github.com/posativ/isso/pull/893
0.12.6 (2022-03-06)
-------------------
- Serve isso.css separately to avoid ``style-src: unsafe-inline`` CSP and allow
clients to override fetch location (#704, ix5):
data-isso-css-url="https://comments.example.org/css/isso.css"
- New "samesite" option in [server] section to override SameSite header for
cookies. (#700, ix5)
- Fallback for SameSite header depending on whether host is served over https
or http (#700, ix5)
- Have client read out shared settings from server. (#311, pellenilsson)
This affects these settings for which ``data-isso-*`` values will be ignored:
[general]
reply-notifications
gravatar
[guard]
reply-to-self
require-author
require-email
- Improved detection of browser-supplied language preferences (#521)
Isso will now honor the newer ``navigator.languages`` global property
as well as ``navigator.language`` and ``navigator.userLanguage``.
There is a new configuration property ``data-isso-default-lang``
that specifies the language to use (instead of English) when none
of these is available. (The existing ``data-isso-lang`` *overrides*
browser-supplied language preferences.)
- Remove ``ISSO_CORS_ORIGIN`` environ variable, which never worked at all
(#803, ix5)
0.12.5 (2021-03-09)
-------------------
- Don't ignore missing configuration files.
(Jelmer Vernooij)
0.12.4 (2021-02-03)
-------------------
- Require Python >= 3.5, for consistency with werkzeug.
(#698, Stefan Gehn)
- Use npm for package installation.
(#695, Stefan Gehn)
- Use sassc. (Stefan Gehn)
- Cope with broken HTTP clients that require specific casing of
"200 OK". (#646, #347, Konzertheld)
- Add European Portuguese translation. (#692, boturon)
- Various doc updates. (ix5)
- Add Turkish translation. (Özcan Oğuz, #669)
- Drop Python 2 support. (Jelmer Vernooij)
0.12.3 (2020-02-22)
-------------------
- New "flags" option in the [markdown] section to customize Misaka's Markdown
HTML rendering. By default, no flags are set.
[markup]
flags = skip-html, escape, hard-wrap
Check docs/configuration/server.rst for more details. #616
* Fix compatibility with newer versions of werkzeug. #614
* Add Python 3.8 support. #600, #615
* New 'latest' endpoint to serve latest comments. #556
* include admin.js in Python Package. #606
* Add a approve-if-email-previously-approved setting.
* Fall back to author names in gravatars (#482)
* Make Isso compatible with Content Security Policies without `script-src 'unsafe-inline'`. #597
* Set subject for notification about new comment, subject should not be empty. #589
* Fix rendering of disabled.html for 'Sub URI' sites.
* contrib: Add Blogger importer tool. #529
* Return 200 with empty array when there are no comments. #301
* Translation updates for Polish, Slovak, Occitan.
* Redirect to comment after moderation. #358
0.12.2 (2019-01-21)
-------------------
- Revert use of labels instead of placeholders, since it breaks
mail notifications. #524
0.12.1 (2019-01-19)
-------------------
- Revert fix for duplicate slashes, as it prevents isso from
starting in some cases. #523
0.12.0 (2019-01-18)
-------------------
- Fix compatibility with new XML API.
- Don't enable admin interface with default password by default. #491
- Add support and documentation for "generic" imports.
- Remove potential duplicate slashes in URLs from
email links. #420
- Add data-isso-reply-notifications to attributes in configuration.
- Use default IP in imports if none is found. Fixes imports of some comments.
- embed: fix feed link creation on older browsers.
- Properly handle to field in mail notifications when using uWSGI spooler
- css: fix vertical alignment of notification checkbox
0.11.1 (2018-11-03)
-------------------
- Include pre-built minified JavaScript and CSS.
0.11.0 (2018-11-03)
-------------------
Bugs & features:
- Fix link in moderation mails if isso is setup on a sub-url (e.g. domain.tld/comments/)
- Add reply notifications
- Add admin interface
- Add links highlighting in comments
- Add apidoc
- Add rc.d script for FreeBSD
- Add the possibility to set CORS Origin through ISSO_CORS_ORIGIN environ variable
- Add preview button
- Add Atom feed at /feed?uri={thread-id}
- Add optionnal gravatar support
- Add nofollow noopener on links inside comments
- Add Dockerfile
- Upgraded to Misaka 2
- Some tests/travis/documentation improvements and fixes + pep8
Translations:
- Fix Chinese translation & typo in CJK
- Add Danish translation
- Add Hungarian translation
- Add Persian translation
- Improvement on german translation
0.10.6 (2016-09-22)
-------------------
- fix missing configuration field
0.10.5 (2016-09-20)
-------------------
- add support for different vote levels, #260
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg.
`"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given
one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg.
put a star on popular comments).
- add new post preview API endpoint, #254
- add an option for mandatory author, #257
- clients can now use `data-title` to get the HTML title for a new page, #252
- add finish translation and other minor bugfixes
0.10.4 (2016-04-12)
-------------------
- fix wrapper attribute when using data-isso-require-mail="true", #238
- fix reponse for OPTIONS response on Python 3, #242
0.10.3 (2016-02-24)
-------------------
- follow redirects, #193
0.10.2 (2016-02-21)
-------------------
- fix getAttribute return value
0.10.1 (2016-02-06)
-------------------
- fix empty author, email and website values when writing a comment
0.10 (2016-02-06)
-----------------
- add new configuration section for hash handling.
[hash]
salt = Eech7co8Ohloopo9Ol6baimi
algorithm = pbkdf2
You can customize the salt, choose different hash functions and tweak the
parameters for PBKDF2.
- Python 3.4+ validate TLS connections against the system's CA. Previously no
validation was in place, see PEP-446__ for details.
- add `fenced_code` and `no_intra_emphasis` to default configuration.
Fenced code allows to write code without indentation using `~~~` delimiters
(optionally with language identifier).
Intra emphasis would compile `foo_bar_baz` to foo<em>bar</em>baz. This
behavior is very confusing for users not knowing the Markdown spec in detail.
- new configuration to require an email when submitting comments, #199. Set
[guard]
require-email = true
and use `data-isso-require-email="true"` to enable this feature. Disabled by
default.
- new Bulgarian translation by sahwar, new Swedish translation by Gustav
Näslund – #143, new Vietnamese translation by Đinh Xuân Sâm, new Croatian
translation by streger, new Czech translation by Jan Chren
- fix SMTP setup without credentials, #174
- version pin Misaka to 1.x, html5lib to 0.9999999
.. __: https://www.python.org/dev/peps/pep-0466/
0.9.10 (2015-04-11)
-------------------
- fix regression in SMTP authentication, #174
0.9.9 (2015-03-04)
------------------
- several Python 3.x related bugfixes
- don't lose comment form if the server rejected the POST request, #144
- add localStorage fallback if QUOTA_EXCEEDED_ERR is thrown (e.g. Safari
private browsing)
- add '--empty-id' flag to Disqus import, because Disqus' export sucks
- (re)gain compatibility with Werkzeug 0.8 and really old html5lib versions
available in Debian Squeeze, #170 & #168
- add User-Agent when Isso requests the URL, an alternate way to #151 (add
'X-Isso' when requesting).
0.9.8 (2014-10-08)
------------------
- add compatibility with configparser==3.5.0b1, #128
0.9.7 (2014-09-25)
------------------
- fix SMTP authentication using CRAM-MD5 (incorrect usage of
`smtplib`), #126
0.9.6 (2014-08-18)
------------------
- remember name, email and website in localStorage, #119
- add option to hide voting feature, #115
data-isso-vote="true|false"
- remove email field from JSON responses
This is a quite serious issue. For the identicon, an expensive hash is used
to avoid the leakage of personal information like a real email address. A
`git blame` reveals, the email has been unintentionally exposed since the very
first release of Isso :-/
The testsuite now contains a dedicated test to prevent this error in the
future.
0.9.5 (2014-08-10)
------------------
- prevent no-break space ( ) insertion to enable manual line breaks using
two trailing spaces (as per Markdown convention), #112
- limit request size to 256 kb, #107
Previously unlimited or limited by proxy server). 256 kb is a rough
approximation of the next database schema with comments limited to 65535
characters and additional fields.
- add support for logging to file, #103
[general]
log-file =
- show timestamp when hovering <time>, #104
- fix a regression when editing comments with multiple paragraphs introduced
in 0.9.3 which would HTML escape manually inserted linebreaks.
0.9.4 (2014-07-09)
------------------
- fixed a regression when using Isso and Gevent
0.9.3 (2014-07-09)
------------------
- remove scrollIntoView while expanding further comments if a fragment is used
(e.g. #isso-thread brought you back to the top, unexpectedly)
- implement a custom Markdown renderer to support multi-line code listings. The
extension "fenced_code" is now enabled by default and generates HTML
compatible with Highlight.js__.
- escape HTML entities when editing a comment with raw HTML
- fix CSS for input
- remove isso.css from binary distribution to avoid confusion (it's still there
from the very first release, but modifications do not work)
.. __: http://highlightjs.org/
0.9 (2014-05-29)
----------------
- comment pagination by Srijan Choudhary, #15
Isso can now limit the amount of comments shown by default and add link to
show more. By default, all top-level comments are shown but only 5 nested
comments (per reply). You can override the settings:
isso-data-max-comments-top="N"
isso-data-max-comments-nested="N"
Where N is a number from 0 to infinity ("inf"). If you limit the amount of
shown top level comments, the overall comment count may be incorrect and a
known issue.
You can also configure the amount of comments shown per click (5 by default):
isso-data-reveal-on-click="N"
This feature also required a change in the comment structure. Previously, all
comments are stored tree-like but shown linearly. To ease the implementation
of pagination, the comment tree is now limited to a maximum depth of one.
Jeff Atwood explains, why `discussions are flat by design`__.
.. __: http://blog.codinghorror.com/web-discussions-flat-by-design/
When you upgrade, Isso will automatically normalize the tree and some
information gets lost. All new replies to a comment are now automatically a
direct child of the top-level comment.
- style improvements by William Dorffer, #39, #84 #90 and #91
Isso now longer uses a fat SCSS library, but plain CSS instead. The design is
now responsive and no longer sets global CSS rules.
- experimental WordPress import, #75
Isso should be able to import WXR 1.0-1.2 exports. The import code is based
on two WXR dumps I found (and created) and may not work for you. Please
report any failure.
- avatar changes, #49
You can now configure the client to not show avatars:
data-isso-avatar="false"
Also there is no longer an avatar shown next to the comment box. This is due
to the new CSS and removes two runtime dependencies.
- you may now set a full From header, #87
[smtp]
from = Foo Bar <spam@local>
- SMTP (all caps) is now recognized for notifications, #95
- Isso now ships a small demo site at /demo, #44
- a few bugfixes: Disqus import now anonymizes IP addresses, uWSGI spooling for
Python 3, HTTP-Referer fallback for HTTP-Origin
- remove Django's PBKDF2 implementation in favour of the PBKDF2 function
available in werkzeug 0.9 or higher. If you're still using werkzeug 0.8, Isso
imports passlib__ as fallback (if available).
This release also features a new templating engine Jade__ which replaces
Markup.js__. Jade can compile directly to JavaScript with a tiny runtime module
on the client. Along with the removal of sha1.js and pbkdf2.js and a few build
optimizations, the JS client now weighs only 40kb (12kb gzipped) – 52kb resp.
17kb before.
.. __: https://pypi.python.org/pypi/passlib
.. __: http://jade-lang.com/
.. __: https://github.com/adammark/Markup.js
0.8 (2014-03-28)
----------------
- replace ``<textarea>`` with ``<div contentedtiable="true">`` to remove the
sluggish auto-resize on input feature. If you use a custom CSS, replace
``textarea`` with ``.textarea`` and also set ``white-space: pre``.
- remove superscript extension from Markdown defaults as it may lead to
unexpected behavior for certain smileys such as "^^". To enable the extension,
add
[markup]
options = superscript
allowed-elements = sup
to your configuration.
- comment count requests are now bundled into a single POST request, but the old
API is still there (deprecated though).
- store *session-key* in database (once generated on database creation). That
means links to activate, edit or delete comments are now always valid even
when you restart Isso.
Currently statically set session keys in ``[general]`` are automatically
migrated into the database on startup and you will get a notice that you can
remove this option.
- fix undefined timestamp when client time differs for more than 1 second.
The human-readable "time ago" deltas have been refined to match `Moment.js`_
behavior.
- avatar colors and background can now be customized:
* ``data-isso-avatar-bg="#f0f0f0"`` sets the background color
* ``data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."`` sets possible
avatar colors (up to 8 colors are possible).
- new [markup] section to customize Misaka's Markdown generation (strikethrough,
superscript and autolink enabled by default). Furthermore, you can now allow
certain HTML elemenets and attributes in the generated output, e.g. to enable
images, set
[markup]
allowed-elements = img
allowed-attributes = src
Check docs/configuration/server.rst for more details.
- replace requirejs-domready with a (self-made) HTML5 idiom, #51
.. _Moment.js: http://momentjs.com/docs/#/displaying/fromnow/
0.7 (2014-01-29)
----------------
- fix malicious HTML injection (due to wrong API usage). All unknown/unsafe
HTML tags are now removed from the output (`html5lib` 0.99(9) or later) or
properly escaped (older `html5lib` versions).
See 36d702c and 3a1f92b for more details.
- remove kriskowal/q JS library (promises implementation) in favour of a
self-made 50 LoC implementation to ease packaging (for Debian), #51
- add documentation to display a comment counter, #56 and #57
- SMTP notifications now support STARTTLS and use this transport security
by default, #48 and #58. This also changes the configuration option from
`ssl = [yes|no]` to `security = [none|starttls|ssl]`.
- translation can now be made (and updated) with Transifex_. If you want to
take ownership for a language, contact me on IRC.
- fix french pluralform
- the (by default random) session-key is now shown on application startup
to make different keys per startup more visible
- use `threading.lock` by default for systems without semaphore support
.. _Transifex: https://www.transifex.com/projects/p/isso/
0.6 (2013-12-16)
----------------
Major improvements:
- override thread discovery with data-isso-id="...", #27
To use the same thread for different URLs, you can now add a custom
``data-isso-id="my-id"`` attribute which is used to identify and retrieve
comments (defaults to current URL aka `window.location.pathname`).
- `isso.dispatch` now dispatches multiple websites (= configurations) based on
URL prefixes
- fix a cross-site request forgery vulnerability for comment creation, voting,
editing and deletion, #40
- show modal dialog to confirm comment deletion and activation, #36
- new, comprehensive documentation based on reST + Sphinx:
http://posativ.org/docs (or docs/ in the repository). Also includes an
annotated `example.conf`, #43
- new italian and russian translations
Minor improvements:
- move `isso:application` to `isso.run:application` to avoid uneccessary
initialization in some cases (change module if you use uWSGI or Gunicorn)
- add Date header to email notifications, #42
- check for blank text in new comment, #41
- work around IE10's HTML5 abilities for custom data-attributes
- add support for Gunicorn (and other pre-forking WSGI servers)
0.5 (2013-11-17)
----------------
Major improvements:
- `listen` option replaces `host` and `port` to support UNIX domain sockets, #25
Instead of `host = localhost` and `port = 8080`, use
`listen = http://localhost:8080`. To listen on a UNIX domain socket, replace
`http://` with `unix://`, e.g. `unix:///tmp/isso.sock`.
- new option `notify` (in the general section) is used to choose (one or more)
notification backends (currently only SMTP is available, though). Isso will
no longer automatically use SMTP for notifications if the initial connection
succeeds.
- new options to control the client integration
* ``data-isso-css="false"`` prevents the client from appending the CSS to the
document. Enabled by default.
* ``data-isso-lang="de"`` overrides the useragent's preferred language (de, en
and fr are currently supported).
* ``data-isso-reply-to-self="true"`` should be set, when you allow reply to
own comments (see server configuration for details).
- add support for `gevent <http://www.gevent.org/>`_, a coroutine-based Python
networking library that uses greenlets (lightweight threads). Recommended
WSGI server when not running with uWSGI (unfortunately stable gevent is not
yet able to listen on a UNIX domain socket).
- fix a serious issue with the voters bloomfilter. During an Isso run, the
ip addresses from all commenters accumulated into the voters bloomfilter
for new comments. Thus, previous commenters could no longer vote other
comments. This fixes the rare occurences of #5.
In addition to this fix, the current voters bloomfilter will be re-initialized
if you are using Isso 0.4 or below (this is not necessary, but on the
other hand, the current bloomfilter for each comment is sort-of useless).
- french translation (thanks to @sploinga), #38
- support for multiple sites, part of #34
Minor improvements:
- `ipaddr` is now used as `ipaddress` fallback for Python 2.6 and 2.7, #32
- changed URL to activate and delete comments to `/id/<N:int>/activate` etc.
- import command uses `<link>` tag instead of `<id>` to extract the relative
URL path, #37
- import command now uses `isDeleted` to mark comments as deleted (and
eventually remove stale comments). This seems to affect only a few comments
from a previous WordPress import into Disqus.
- import command lists orphaned comments after import.
- import command now has a ``--dry-run`` option to do no actual operation on
the database.
0.4 (2013-11-05)
----------------
- Isso now handles cross-domain requests and cookies, fixes #24
- Isso for Python 2.x now supports werkzeug>=0.8
- limit email length to 254 to avoid Hash-DDoS
- override Isso API location with ``data-isso="..."`` in the script tag
- override HTML title parsing with a custom ``data-title="..."`` attribute
in ``<div id="isso-thread"></div>``
0.3 (2013-11-01)
----------------
- improve initial comment loading performance in the client
- cache slow REST requests, see #18
- add a SQLite trigger that detects and removes stale threads (= threads,
with all comments being removed) from the database when a comment is
removed.
- PyPi releases now include an uncompressed version of the JavaScript
files -- `embed.dev.js` and `count.dev.js` -- to track down errors.
- use uWSGI's internal locking instead of a self-made shared memory lock
0.2 (2013-10-29)
----------------
- initial PyPi release
| fliiiix | 7468a2cd28eb0bf55950d2ec545a9555e4e2ff93 | e1a629160dc8aed849d34c5478e6f54c4a789481 | Simply "Python 3.11 support" | ix5 | 53 |
posativ/isso | 828 | docs: update list of alternatives | The list was quiet outdated with abandoned projects, so i updated it.
Also added link to a great overview with all known open source comment servers.
The link is quiet long and breaks the 80 chars convention. How to handle that?
A different option for the heading would be "Alternatives". Let me know what you prefer!
Builds correctly:
![Screenshot from 2022-03-23 17-49-30](https://user-images.githubusercontent.com/91113/159752824-9d21401e-4def-4274-b7ea-f0daae21c088.png)
| null | 2022-03-22 21:42:40+00:00 | 2022-03-23 16:54:08+00:00 | docs/docs/index.rst | Overview
========
Welcome to Isso's documentation. This documentation will help you get started
fast. If you run into any problems when using Isso, you can find the answer in
troubleshooting guide or you can ask me on IRC or GitHub.
Documentation overview:
.. toctree::
:maxdepth: 1
install
quickstart
troubleshooting
What's Isso?
------------
Isso is a lightweight commenting server similar to Disqus. It allows anonymous
comments, maintains identity and is simple to administrate. It uses JavaScript
and cross-origin ressource sharing for easy integration into (static) websites.
No, I meant "Isso"
------------------
Isso is an informal, german abbreviation for "Ich schrei sonst!", which can
roughly be translated to "I'm yelling otherwise". It usually ends the
discussion without any further arguments.
In germany, Isso `is also pokémon N° 360`__.
.. __: http://bulbapedia.bulbagarden.net/wiki/Wynaut_(Pok%C3%A9mon)
What's wrong with Disqus?
-------------------------
No anonymous comments (IP address, email and name recorded), hosted in the USA,
third-party. Just like IntenseDebate, livefrye etc. When you embed Disqus, they
can do anything with your readers (and probably mine Bitcoins, see the loading
times).
Isso is not the only open-source commenting server:
* `commento <https://commento.io/>`_, written in Go. Requires a
`postgresql <https://www.postgresql.org/>`_ database.
* `Remark42 <https://remark42.com/docs/1.6/>`_, written in Go.
* `talkatv <https://github.com/talkatv/talkatv>`_, written in Python.
Unfortunately, talkatv's (read "talkative") development stalled. Neither
anonymous nor threaded comments.
* `Juvia <https://github.com/phusion/juvia>`_, written in Ruby (on Rails).
No threaded comments, nice administration webinterface, but... yeah... Ruby.
* `Tildehash.com <http://www.tildehash.com/?article=why-im-reinventing-disqus>`_,
written in PHP__ (compare to Python__). Did I forgot something?
* `Unobtrusive, self-hosted comments <http://stackoverflow.com/q/2053217>`_,
discussion on StackOverflow.
.. __: http://www.cvedetails.com/vendor/74/PHP.html
.. __: http://www.cvedetails.com/vendor/10210/Python.html
| Overview
========
Welcome to Isso's documentation. This documentation will help you get started
fast. If you run into any problems when using Isso, you can find the answer in
troubleshooting guide or you can ask me on IRC or GitHub.
Documentation overview:
.. toctree::
:maxdepth: 1
install
quickstart
troubleshooting
What's Isso?
------------
Isso is a lightweight commenting server similar to Disqus. It allows anonymous
comments, maintains identity and is simple to administrate. It uses JavaScript
and cross-origin ressource sharing for easy integration into (static) websites.
No, I meant "Isso"
------------------
Isso is an informal, german abbreviation for "Ich schrei sonst!", which can
roughly be translated to "I'm yelling otherwise". It usually ends the
discussion without any further arguments.
In germany, Isso `is also pokémon N° 360`__.
.. __: http://bulbapedia.bulbagarden.net/wiki/Wynaut_(Pok%C3%A9mon)
What's wrong with Disqus?
-------------------------
No anonymous comments (IP address, email and name recorded), hosted in the USA,
third-party. Just like IntenseDebate etc. When you embed Disqus, they
can do anything with your readers (and probably mine Bitcoins, see the loading
times).
Other options
-------------
Isso is not the only open-source commenting server. You can find an overview at
`lisakov.com: Open source comments <https://lisakov.com/projects/open-source-comments/>`_.
Some popular options are:
* `Commento <https://commento.io/>`_, written in Go. Requires a
`PostgreSQL <https://www.postgresql.org/>`_ database.
* `Remark42 <https://remark42.com/>`_, written in Go.
* `Staticman <https://staticman.net/>`_, written in Node.js. Adds comments
directly to repository of static sites.
* `schnack <https://schnack.cool/>`_, written in Node.js.
| davidak | 7ef6e054ae6b971770d67daaa8d08ee25911ef4d | 8c306f45a24b6996d2fcc44d6564a552021ed03d | While you're at it: It's `PostgreSQL` | ix5 | 54 |
posativ/isso | 828 | docs: update list of alternatives | The list was quiet outdated with abandoned projects, so i updated it.
Also added link to a great overview with all known open source comment servers.
The link is quiet long and breaks the 80 chars convention. How to handle that?
A different option for the heading would be "Alternatives". Let me know what you prefer!
Builds correctly:
![Screenshot from 2022-03-23 17-49-30](https://user-images.githubusercontent.com/91113/159752824-9d21401e-4def-4274-b7ea-f0daae21c088.png)
| null | 2022-03-22 21:42:40+00:00 | 2022-03-23 16:54:08+00:00 | docs/docs/index.rst | Overview
========
Welcome to Isso's documentation. This documentation will help you get started
fast. If you run into any problems when using Isso, you can find the answer in
troubleshooting guide or you can ask me on IRC or GitHub.
Documentation overview:
.. toctree::
:maxdepth: 1
install
quickstart
troubleshooting
What's Isso?
------------
Isso is a lightweight commenting server similar to Disqus. It allows anonymous
comments, maintains identity and is simple to administrate. It uses JavaScript
and cross-origin ressource sharing for easy integration into (static) websites.
No, I meant "Isso"
------------------
Isso is an informal, german abbreviation for "Ich schrei sonst!", which can
roughly be translated to "I'm yelling otherwise". It usually ends the
discussion without any further arguments.
In germany, Isso `is also pokémon N° 360`__.
.. __: http://bulbapedia.bulbagarden.net/wiki/Wynaut_(Pok%C3%A9mon)
What's wrong with Disqus?
-------------------------
No anonymous comments (IP address, email and name recorded), hosted in the USA,
third-party. Just like IntenseDebate, livefrye etc. When you embed Disqus, they
can do anything with your readers (and probably mine Bitcoins, see the loading
times).
Isso is not the only open-source commenting server:
* `commento <https://commento.io/>`_, written in Go. Requires a
`postgresql <https://www.postgresql.org/>`_ database.
* `Remark42 <https://remark42.com/docs/1.6/>`_, written in Go.
* `talkatv <https://github.com/talkatv/talkatv>`_, written in Python.
Unfortunately, talkatv's (read "talkative") development stalled. Neither
anonymous nor threaded comments.
* `Juvia <https://github.com/phusion/juvia>`_, written in Ruby (on Rails).
No threaded comments, nice administration webinterface, but... yeah... Ruby.
* `Tildehash.com <http://www.tildehash.com/?article=why-im-reinventing-disqus>`_,
written in PHP__ (compare to Python__). Did I forgot something?
* `Unobtrusive, self-hosted comments <http://stackoverflow.com/q/2053217>`_,
discussion on StackOverflow.
.. __: http://www.cvedetails.com/vendor/74/PHP.html
.. __: http://www.cvedetails.com/vendor/10210/Python.html
| Overview
========
Welcome to Isso's documentation. This documentation will help you get started
fast. If you run into any problems when using Isso, you can find the answer in
troubleshooting guide or you can ask me on IRC or GitHub.
Documentation overview:
.. toctree::
:maxdepth: 1
install
quickstart
troubleshooting
What's Isso?
------------
Isso is a lightweight commenting server similar to Disqus. It allows anonymous
comments, maintains identity and is simple to administrate. It uses JavaScript
and cross-origin ressource sharing for easy integration into (static) websites.
No, I meant "Isso"
------------------
Isso is an informal, german abbreviation for "Ich schrei sonst!", which can
roughly be translated to "I'm yelling otherwise". It usually ends the
discussion without any further arguments.
In germany, Isso `is also pokémon N° 360`__.
.. __: http://bulbapedia.bulbagarden.net/wiki/Wynaut_(Pok%C3%A9mon)
What's wrong with Disqus?
-------------------------
No anonymous comments (IP address, email and name recorded), hosted in the USA,
third-party. Just like IntenseDebate etc. When you embed Disqus, they
can do anything with your readers (and probably mine Bitcoins, see the loading
times).
Other options
-------------
Isso is not the only open-source commenting server. You can find an overview at
`lisakov.com: Open source comments <https://lisakov.com/projects/open-source-comments/>`_.
Some popular options are:
* `Commento <https://commento.io/>`_, written in Go. Requires a
`PostgreSQL <https://www.postgresql.org/>`_ database.
* `Remark42 <https://remark42.com/>`_, written in Go.
* `Staticman <https://staticman.net/>`_, written in Node.js. Adds comments
directly to repository of static sites.
* `schnack <https://schnack.cool/>`_, written in Node.js.
| davidak | 7ef6e054ae6b971770d67daaa8d08ee25911ef4d | 8c306f45a24b6996d2fcc44d6564a552021ed03d | Link title might say "lisakov.com: Open-source comments" or just "lisakov.com"
Also, don't worry about any line length limits here. | ix5 | 55 |
posativ/isso | 828 | docs: update list of alternatives | The list was quiet outdated with abandoned projects, so i updated it.
Also added link to a great overview with all known open source comment servers.
The link is quiet long and breaks the 80 chars convention. How to handle that?
A different option for the heading would be "Alternatives". Let me know what you prefer!
Builds correctly:
![Screenshot from 2022-03-23 17-49-30](https://user-images.githubusercontent.com/91113/159752824-9d21401e-4def-4274-b7ea-f0daae21c088.png)
| null | 2022-03-22 21:42:40+00:00 | 2022-03-23 16:54:08+00:00 | docs/docs/index.rst | Overview
========
Welcome to Isso's documentation. This documentation will help you get started
fast. If you run into any problems when using Isso, you can find the answer in
troubleshooting guide or you can ask me on IRC or GitHub.
Documentation overview:
.. toctree::
:maxdepth: 1
install
quickstart
troubleshooting
What's Isso?
------------
Isso is a lightweight commenting server similar to Disqus. It allows anonymous
comments, maintains identity and is simple to administrate. It uses JavaScript
and cross-origin ressource sharing for easy integration into (static) websites.
No, I meant "Isso"
------------------
Isso is an informal, german abbreviation for "Ich schrei sonst!", which can
roughly be translated to "I'm yelling otherwise". It usually ends the
discussion without any further arguments.
In germany, Isso `is also pokémon N° 360`__.
.. __: http://bulbapedia.bulbagarden.net/wiki/Wynaut_(Pok%C3%A9mon)
What's wrong with Disqus?
-------------------------
No anonymous comments (IP address, email and name recorded), hosted in the USA,
third-party. Just like IntenseDebate, livefrye etc. When you embed Disqus, they
can do anything with your readers (and probably mine Bitcoins, see the loading
times).
Isso is not the only open-source commenting server:
* `commento <https://commento.io/>`_, written in Go. Requires a
`postgresql <https://www.postgresql.org/>`_ database.
* `Remark42 <https://remark42.com/docs/1.6/>`_, written in Go.
* `talkatv <https://github.com/talkatv/talkatv>`_, written in Python.
Unfortunately, talkatv's (read "talkative") development stalled. Neither
anonymous nor threaded comments.
* `Juvia <https://github.com/phusion/juvia>`_, written in Ruby (on Rails).
No threaded comments, nice administration webinterface, but... yeah... Ruby.
* `Tildehash.com <http://www.tildehash.com/?article=why-im-reinventing-disqus>`_,
written in PHP__ (compare to Python__). Did I forgot something?
* `Unobtrusive, self-hosted comments <http://stackoverflow.com/q/2053217>`_,
discussion on StackOverflow.
.. __: http://www.cvedetails.com/vendor/74/PHP.html
.. __: http://www.cvedetails.com/vendor/10210/Python.html
| Overview
========
Welcome to Isso's documentation. This documentation will help you get started
fast. If you run into any problems when using Isso, you can find the answer in
troubleshooting guide or you can ask me on IRC or GitHub.
Documentation overview:
.. toctree::
:maxdepth: 1
install
quickstart
troubleshooting
What's Isso?
------------
Isso is a lightweight commenting server similar to Disqus. It allows anonymous
comments, maintains identity and is simple to administrate. It uses JavaScript
and cross-origin ressource sharing for easy integration into (static) websites.
No, I meant "Isso"
------------------
Isso is an informal, german abbreviation for "Ich schrei sonst!", which can
roughly be translated to "I'm yelling otherwise". It usually ends the
discussion without any further arguments.
In germany, Isso `is also pokémon N° 360`__.
.. __: http://bulbapedia.bulbagarden.net/wiki/Wynaut_(Pok%C3%A9mon)
What's wrong with Disqus?
-------------------------
No anonymous comments (IP address, email and name recorded), hosted in the USA,
third-party. Just like IntenseDebate etc. When you embed Disqus, they
can do anything with your readers (and probably mine Bitcoins, see the loading
times).
Other options
-------------
Isso is not the only open-source commenting server. You can find an overview at
`lisakov.com: Open source comments <https://lisakov.com/projects/open-source-comments/>`_.
Some popular options are:
* `Commento <https://commento.io/>`_, written in Go. Requires a
`PostgreSQL <https://www.postgresql.org/>`_ database.
* `Remark42 <https://remark42.com/>`_, written in Go.
* `Staticman <https://staticman.net/>`_, written in Node.js. Adds comments
directly to repository of static sites.
* `schnack <https://schnack.cool/>`_, written in Node.js.
| davidak | 7ef6e054ae6b971770d67daaa8d08ee25911ef4d | 8c306f45a24b6996d2fcc44d6564a552021ed03d | LiveFyre also doesn't seem to exist any more | ix5 | 56 |
posativ/isso | 821 | [client] js: Fetch public conf once from /config; embed.js: Preserve default config values | ### isso: js: embed.js: Preserve default config values
This way, Isso is not confusing users when a server config value overwrites a client default one, i.e. if the user has not actually attempted to overwrite it.
### isso: js, py: Fetch public conf once from /config
This is an improvement on top of: 02f3ea0658680ce200258bc66d509403846b62d5 "Have client read out shared settings from server (#311)"
So far, the `config` dict was being sent with the server response when fetching comments from the `fetch()` `/` (GET) endpoint.
Remove the `config` object from `fetch()` responses and instead let client user the newly created `/config` endpoint. (see #880)
Extend the JS client api file to fetch from the `/config` endpoint, which will only happen once via the `fetchComments` hook on page load.
**EDIT:** Have a couple of nasty race conditions right now, needs further work. Caused by multiple instances of `config` copying from `default_config`, where the templates might receive either a pre-copy or post-copy instance. | null | 2022-03-20 22:02:58+00:00 | 2022-06-05 17:53:26+00:00 | isso/js/app/config.js | var utils = require("app/utils");
"use strict";
var config = {
"css": true,
"css-url": null,
"lang": null,
"default-lang": "en",
"reply-to-self": false,
"require-email": false,
"require-author": false,
"reply-notifications": false,
"reply-notifications-default-enabled": false,
"max-comments-top": "inf",
"max-comments-nested": 5,
"reveal-on-click": 5,
"gravatar": false,
"avatar": true,
"avatar-bg": "#f0f0f0",
"avatar-fg": ["#9abf88", "#5698c4", "#e279a3", "#9163b6",
"#be5168", "#f19670", "#e4bf80", "#447c69"].join(" "),
"vote": true,
"vote-levels": null,
"feed": false,
"page-author-hashes": "",
};
var js = document.getElementsByTagName("script");
for (var i = 0; i < js.length; i++) {
for (var j = 0; j < js[i].attributes.length; j++) {
var attr = js[i].attributes[j];
if (/^data-isso-/.test(attr.name)) {
try {
config[attr.name.substring(10)] = JSON.parse(attr.value);
} catch (ex) {
config[attr.name.substring(10)] = attr.value;
}
}
}
}
// split avatar-fg on whitespace
config["avatar-fg"] = config["avatar-fg"].split(" ");
// create an array of normalized language codes from:
// - config["lang"], if it is nonempty
// - the first of navigator.languages, navigator.language, and
// navigator.userLanguage that exists and has a nonempty value
// - config["default-lang"]
// - "en" as an ultimate fallback
// i18n.js will use the first code in this array for which we have
// a translation.
var languages = [];
var found_navlang = false;
if (config["lang"]) {
languages.push(utils.normalize_bcp47(config["lang"]));
}
if (navigator.languages) {
for (i = 0; i < navigator.languages.length; i++) {
if (navigator.languages[i]) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.languages[i]));
}
}
}
if (!found_navlang && navigator.language) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.language));
}
if (!found_navlang && navigator.userLanguage) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.userLanguage));
}
if (config["default-lang"]) {
languages.push(utils.normalize_bcp47(config["default-lang"]));
}
languages.push("en");
config["langs"] = languages;
// code outside this file should look only at langs
delete config["lang"];
delete config["default-lang"];
// Convert page-author-hash into a array by splitting at whitespace and/or commas
config["page-author-hashes"] = config["page-author-hashes"].split(/[\s,]+/);
module.exports = config;
| var default_config = require("app/default_config");
var utils = require("app/utils");
"use strict";
// Preserve default values to filter out when comparing
// with values fetched from server
var config = {};
for (var key in default_config) {
config[key] = default_config[key];
}
var js = document.getElementsByTagName("script");
for (var i = 0; i < js.length; i++) {
for (var j = 0; j < js[i].attributes.length; j++) {
var attr = js[i].attributes[j];
if (/^data-isso-/.test(attr.name)) {
try {
config[attr.name.substring(10)] = JSON.parse(attr.value);
} catch (ex) {
config[attr.name.substring(10)] = attr.value;
}
}
}
}
// split avatar-fg on whitespace
config["avatar-fg"] = config["avatar-fg"].split(" ");
// create an array of normalized language codes from:
// - config["lang"], if it is nonempty
// - the first of navigator.languages, navigator.language, and
// navigator.userLanguage that exists and has a nonempty value
// - config["default-lang"]
// - "en" as an ultimate fallback
// i18n.js will use the first code in this array for which we have
// a translation.
var languages = [];
var found_navlang = false;
if (config["lang"]) {
languages.push(utils.normalize_bcp47(config["lang"]));
}
if (navigator.languages) {
for (i = 0; i < navigator.languages.length; i++) {
if (navigator.languages[i]) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.languages[i]));
}
}
}
if (!found_navlang && navigator.language) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.language));
}
if (!found_navlang && navigator.userLanguage) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.userLanguage));
}
if (config["default-lang"]) {
languages.push(utils.normalize_bcp47(config["default-lang"]));
}
languages.push("en");
config["langs"] = languages;
// code outside this file should look only at langs
delete config["lang"];
delete config["default-lang"];
// Convert page-author-hash into a array by splitting at whitespace and/or commas
config["page-author-hashes"] = config["page-author-hashes"].split(/[\s,]+/);
module.exports = config;
| ix5 | aaa8476fbc41400d3f70f23a1c68b22829b5ceac | 628246c82c6fb00024a7a8a523ee4b3ba622d76c | If anyone has a cleaner way to clone a dict-like objekt in JS, please let me know. | ix5 | 57 |
posativ/isso | 821 | [client] js: Fetch public conf once from /config; embed.js: Preserve default config values | ### isso: js: embed.js: Preserve default config values
This way, Isso is not confusing users when a server config value overwrites a client default one, i.e. if the user has not actually attempted to overwrite it.
### isso: js, py: Fetch public conf once from /config
This is an improvement on top of: 02f3ea0658680ce200258bc66d509403846b62d5 "Have client read out shared settings from server (#311)"
So far, the `config` dict was being sent with the server response when fetching comments from the `fetch()` `/` (GET) endpoint.
Remove the `config` object from `fetch()` responses and instead let client user the newly created `/config` endpoint. (see #880)
Extend the JS client api file to fetch from the `/config` endpoint, which will only happen once via the `fetchComments` hook on page load.
**EDIT:** Have a couple of nasty race conditions right now, needs further work. Caused by multiple instances of `config` copying from `default_config`, where the templates might receive either a pre-copy or post-copy instance. | null | 2022-03-20 22:02:58+00:00 | 2022-06-05 17:53:26+00:00 | isso/js/app/config.js | var utils = require("app/utils");
"use strict";
var config = {
"css": true,
"css-url": null,
"lang": null,
"default-lang": "en",
"reply-to-self": false,
"require-email": false,
"require-author": false,
"reply-notifications": false,
"reply-notifications-default-enabled": false,
"max-comments-top": "inf",
"max-comments-nested": 5,
"reveal-on-click": 5,
"gravatar": false,
"avatar": true,
"avatar-bg": "#f0f0f0",
"avatar-fg": ["#9abf88", "#5698c4", "#e279a3", "#9163b6",
"#be5168", "#f19670", "#e4bf80", "#447c69"].join(" "),
"vote": true,
"vote-levels": null,
"feed": false,
"page-author-hashes": "",
};
var js = document.getElementsByTagName("script");
for (var i = 0; i < js.length; i++) {
for (var j = 0; j < js[i].attributes.length; j++) {
var attr = js[i].attributes[j];
if (/^data-isso-/.test(attr.name)) {
try {
config[attr.name.substring(10)] = JSON.parse(attr.value);
} catch (ex) {
config[attr.name.substring(10)] = attr.value;
}
}
}
}
// split avatar-fg on whitespace
config["avatar-fg"] = config["avatar-fg"].split(" ");
// create an array of normalized language codes from:
// - config["lang"], if it is nonempty
// - the first of navigator.languages, navigator.language, and
// navigator.userLanguage that exists and has a nonempty value
// - config["default-lang"]
// - "en" as an ultimate fallback
// i18n.js will use the first code in this array for which we have
// a translation.
var languages = [];
var found_navlang = false;
if (config["lang"]) {
languages.push(utils.normalize_bcp47(config["lang"]));
}
if (navigator.languages) {
for (i = 0; i < navigator.languages.length; i++) {
if (navigator.languages[i]) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.languages[i]));
}
}
}
if (!found_navlang && navigator.language) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.language));
}
if (!found_navlang && navigator.userLanguage) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.userLanguage));
}
if (config["default-lang"]) {
languages.push(utils.normalize_bcp47(config["default-lang"]));
}
languages.push("en");
config["langs"] = languages;
// code outside this file should look only at langs
delete config["lang"];
delete config["default-lang"];
// Convert page-author-hash into a array by splitting at whitespace and/or commas
config["page-author-hashes"] = config["page-author-hashes"].split(/[\s,]+/);
module.exports = config;
| var default_config = require("app/default_config");
var utils = require("app/utils");
"use strict";
// Preserve default values to filter out when comparing
// with values fetched from server
var config = {};
for (var key in default_config) {
config[key] = default_config[key];
}
var js = document.getElementsByTagName("script");
for (var i = 0; i < js.length; i++) {
for (var j = 0; j < js[i].attributes.length; j++) {
var attr = js[i].attributes[j];
if (/^data-isso-/.test(attr.name)) {
try {
config[attr.name.substring(10)] = JSON.parse(attr.value);
} catch (ex) {
config[attr.name.substring(10)] = attr.value;
}
}
}
}
// split avatar-fg on whitespace
config["avatar-fg"] = config["avatar-fg"].split(" ");
// create an array of normalized language codes from:
// - config["lang"], if it is nonempty
// - the first of navigator.languages, navigator.language, and
// navigator.userLanguage that exists and has a nonempty value
// - config["default-lang"]
// - "en" as an ultimate fallback
// i18n.js will use the first code in this array for which we have
// a translation.
var languages = [];
var found_navlang = false;
if (config["lang"]) {
languages.push(utils.normalize_bcp47(config["lang"]));
}
if (navigator.languages) {
for (i = 0; i < navigator.languages.length; i++) {
if (navigator.languages[i]) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.languages[i]));
}
}
}
if (!found_navlang && navigator.language) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.language));
}
if (!found_navlang && navigator.userLanguage) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.userLanguage));
}
if (config["default-lang"]) {
languages.push(utils.normalize_bcp47(config["default-lang"]));
}
languages.push("en");
config["langs"] = languages;
// code outside this file should look only at langs
delete config["lang"];
delete config["default-lang"];
// Convert page-author-hash into a array by splitting at whitespace and/or commas
config["page-author-hashes"] = config["page-author-hashes"].split(/[\s,]+/);
module.exports = config;
| ix5 | aaa8476fbc41400d3f70f23a1c68b22829b5ceac | 628246c82c6fb00024a7a8a523ee4b3ba622d76c | What about this?
```js
var config = { ...default_config };
``` | Kerumen | 58 |
posativ/isso | 821 | [client] js: Fetch public conf once from /config; embed.js: Preserve default config values | ### isso: js: embed.js: Preserve default config values
This way, Isso is not confusing users when a server config value overwrites a client default one, i.e. if the user has not actually attempted to overwrite it.
### isso: js, py: Fetch public conf once from /config
This is an improvement on top of: 02f3ea0658680ce200258bc66d509403846b62d5 "Have client read out shared settings from server (#311)"
So far, the `config` dict was being sent with the server response when fetching comments from the `fetch()` `/` (GET) endpoint.
Remove the `config` object from `fetch()` responses and instead let client user the newly created `/config` endpoint. (see #880)
Extend the JS client api file to fetch from the `/config` endpoint, which will only happen once via the `fetchComments` hook on page load.
**EDIT:** Have a couple of nasty race conditions right now, needs further work. Caused by multiple instances of `config` copying from `default_config`, where the templates might receive either a pre-copy or post-copy instance. | null | 2022-03-20 22:02:58+00:00 | 2022-06-05 17:53:26+00:00 | isso/js/app/config.js | var utils = require("app/utils");
"use strict";
var config = {
"css": true,
"css-url": null,
"lang": null,
"default-lang": "en",
"reply-to-self": false,
"require-email": false,
"require-author": false,
"reply-notifications": false,
"reply-notifications-default-enabled": false,
"max-comments-top": "inf",
"max-comments-nested": 5,
"reveal-on-click": 5,
"gravatar": false,
"avatar": true,
"avatar-bg": "#f0f0f0",
"avatar-fg": ["#9abf88", "#5698c4", "#e279a3", "#9163b6",
"#be5168", "#f19670", "#e4bf80", "#447c69"].join(" "),
"vote": true,
"vote-levels": null,
"feed": false,
"page-author-hashes": "",
};
var js = document.getElementsByTagName("script");
for (var i = 0; i < js.length; i++) {
for (var j = 0; j < js[i].attributes.length; j++) {
var attr = js[i].attributes[j];
if (/^data-isso-/.test(attr.name)) {
try {
config[attr.name.substring(10)] = JSON.parse(attr.value);
} catch (ex) {
config[attr.name.substring(10)] = attr.value;
}
}
}
}
// split avatar-fg on whitespace
config["avatar-fg"] = config["avatar-fg"].split(" ");
// create an array of normalized language codes from:
// - config["lang"], if it is nonempty
// - the first of navigator.languages, navigator.language, and
// navigator.userLanguage that exists and has a nonempty value
// - config["default-lang"]
// - "en" as an ultimate fallback
// i18n.js will use the first code in this array for which we have
// a translation.
var languages = [];
var found_navlang = false;
if (config["lang"]) {
languages.push(utils.normalize_bcp47(config["lang"]));
}
if (navigator.languages) {
for (i = 0; i < navigator.languages.length; i++) {
if (navigator.languages[i]) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.languages[i]));
}
}
}
if (!found_navlang && navigator.language) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.language));
}
if (!found_navlang && navigator.userLanguage) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.userLanguage));
}
if (config["default-lang"]) {
languages.push(utils.normalize_bcp47(config["default-lang"]));
}
languages.push("en");
config["langs"] = languages;
// code outside this file should look only at langs
delete config["lang"];
delete config["default-lang"];
// Convert page-author-hash into a array by splitting at whitespace and/or commas
config["page-author-hashes"] = config["page-author-hashes"].split(/[\s,]+/);
module.exports = config;
| var default_config = require("app/default_config");
var utils = require("app/utils");
"use strict";
// Preserve default values to filter out when comparing
// with values fetched from server
var config = {};
for (var key in default_config) {
config[key] = default_config[key];
}
var js = document.getElementsByTagName("script");
for (var i = 0; i < js.length; i++) {
for (var j = 0; j < js[i].attributes.length; j++) {
var attr = js[i].attributes[j];
if (/^data-isso-/.test(attr.name)) {
try {
config[attr.name.substring(10)] = JSON.parse(attr.value);
} catch (ex) {
config[attr.name.substring(10)] = attr.value;
}
}
}
}
// split avatar-fg on whitespace
config["avatar-fg"] = config["avatar-fg"].split(" ");
// create an array of normalized language codes from:
// - config["lang"], if it is nonempty
// - the first of navigator.languages, navigator.language, and
// navigator.userLanguage that exists and has a nonempty value
// - config["default-lang"]
// - "en" as an ultimate fallback
// i18n.js will use the first code in this array for which we have
// a translation.
var languages = [];
var found_navlang = false;
if (config["lang"]) {
languages.push(utils.normalize_bcp47(config["lang"]));
}
if (navigator.languages) {
for (i = 0; i < navigator.languages.length; i++) {
if (navigator.languages[i]) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.languages[i]));
}
}
}
if (!found_navlang && navigator.language) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.language));
}
if (!found_navlang && navigator.userLanguage) {
found_navlang = true;
languages.push(utils.normalize_bcp47(navigator.userLanguage));
}
if (config["default-lang"]) {
languages.push(utils.normalize_bcp47(config["default-lang"]));
}
languages.push("en");
config["langs"] = languages;
// code outside this file should look only at langs
delete config["lang"];
delete config["default-lang"];
// Convert page-author-hash into a array by splitting at whitespace and/or commas
config["page-author-hashes"] = config["page-author-hashes"].split(/[\s,]+/);
module.exports = config;
| ix5 | aaa8476fbc41400d3f70f23a1c68b22829b5ceac | 628246c82c6fb00024a7a8a523ee4b3ba622d76c | Destructuring was on my "not-sure-we-can-do-that-without-throwing-old-browsers-under-the-bus"-list. But I've used that syntax for the template files already, so I might use it here as well.
Btw, I really appreciate the two of you, @Kerumen and @adroste, weighing in on these issues. It's a lot of work to wrangle all this JS and nice to have good advice from people more knowledgeable on this topic. | ix5 | 59 |
posativ/isso | 808 | setup.py: drop python3.5 support | Since not tests are run for 3.5 drop support
with the next release.
Also Python 3.5 has reached end-of-life on 5-Sep-2020.
Python 3.5.10 is the final release of 3.5.
https://www.python.org/downloads/release/python-3510/ | null | 2022-03-06 14:09:53+00:00 | 2022-03-27 21:45:09+00:00 | CHANGES.rst | Changelog for Isso
==================
%(version)s (%(date)s)
0.12.6 (2022-03-06)
-------------------
- Serve isso.css separately to avoid ``style-src: unsafe-inline`` CSP and allow
clients to override fetch location (#704, ix5):
data-isso-css-url="https://comments.example.org/css/isso.css"
- New "samesite" option in [server] section to override SameSite header for
cookies. (#700, ix5)
- Fallback for SameSite header depending on whether host is served over https
or http (#700, ix5)
- Have client read out shared settings from server. (#311, pellenilsson)
This affects these settings for which ``data-isso-*`` values will be ignored:
[general]
reply-notifications
gravatar
[guard]
reply-to-self
require-author
require-email
- Improved detection of browser-supplied language preferences (#521)
Isso will now honor the newer ``navigator.languages`` global property
as well as ``navigator.language`` and ``navigator.userLanguage``.
There is a new configuration property ``data-isso-default-lang``
that specifies the language to use (instead of English) when none
of these is available. (The existing ``data-isso-lang`` *overrides*
browser-supplied language preferences.)
- Remove ``ISSO_CORS_ORIGIN`` environ variable, which never worked at all
(#803, ix5)
0.12.5 (2021-03-09)
-------------------
- Don't ignore missing configuration files.
(Jelmer Vernooij)
0.12.4 (2021-02-03)
-------------------
- Require Python >= 3.5, for consistency with werkzeug.
(#698, Stefan Gehn)
- Use npm for package installation.
(#695, Stefan Gehn)
- Use sassc. (Stefan Gehn)
- Cope with broken HTTP clients that require specific casing of
"200 OK". (#646, #347, Konzertheld)
- Add European Portuguese translation. (#692, boturon)
- Various doc updates. (ix5)
- Add Turkish translation. (Özcan Oğuz, #669)
- Drop Python 2 support. (Jelmer Vernooij)
0.12.3 (2020-02-22)
-------------------
- New "flags" option in the [markdown] section to customize Misaka's Markdown
HTML rendering. By default, no flags are set.
[markup]
flags = skip-html, escape, hard-wrap
Check docs/configuration/server.rst for more details. #616
* Fix compatibility with newer versions of werkzeug. #614
* Add Python 3.8 support. #600, #615
* New 'latest' endpoint to serve latest comments. #556
* include admin.js in Python Package. #606
* Add a approve-if-email-previously-approved setting.
* Fall back to author names in gravatars (#482)
* Make Isso compatible with Content Security Policies without `script-src 'unsafe-inline'`. #597
* Set subject for notification about new comment, subject should not be empty. #589
* Fix rendering of disabled.html for 'Sub URI' sites.
* contrib: Add Blogger importer tool. #529
* Return 200 with empty array when there are no comments. #301
* Translation updates for Polish, Slovak, Occitan.
* Redirect to comment after moderation. #358
0.12.2 (2019-01-21)
-------------------
- Revert use of labels instead of placeholders, since it breaks
mail notifications. #524
0.12.1 (2019-01-19)
-------------------
- Revert fix for duplicate slashes, as it prevents isso from
starting in some cases. #523
0.12.0 (2019-01-18)
-------------------
- Fix compatibility with new XML API.
- Don't enable admin interface with default password by default. #491
- Add support and documentation for "generic" imports.
- Remove potential duplicate slashes in URLs from
email links. #420
- Add data-isso-reply-notifications to attributes in configuration.
- Use default IP in imports if none is found. Fixes imports of some comments.
- embed: fix feed link creation on older browsers.
- Properly handle to field in mail notifications when using uWSGI spooler
- css: fix vertical alignment of notification checkbox
0.11.1 (2018-11-03)
-------------------
- Include pre-built minified JavaScript and CSS.
0.11.0 (2018-11-03)
-------------------
Bugs & features:
- Fix link in moderation mails if isso is setup on a sub-url (e.g. domain.tld/comments/)
- Add reply notifications
- Add admin interface
- Add links highlighting in comments
- Add apidoc
- Add rc.d script for FreeBSD
- Add the possibility to set CORS Origin through ISSO_CORS_ORIGIN environ variable
- Add preview button
- Add Atom feed at /feed?uri={thread-id}
- Add optionnal gravatar support
- Add nofollow noopener on links inside comments
- Add Dockerfile
- Upgraded to Misaka 2
- Some tests/travis/documentation improvements and fixes + pep8
Translations:
- Fix Chinese translation & typo in CJK
- Add Danish translation
- Add Hungarian translation
- Add Persian translation
- Improvement on german translation
0.10.6 (2016-09-22)
-------------------
- fix missing configuration field
0.10.5 (2016-09-20)
-------------------
- add support for different vote levels, #260
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg.
`"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given
one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg.
put a star on popular comments).
- add new post preview API endpoint, #254
- add an option for mandatory author, #257
- clients can now use `data-title` to get the HTML title for a new page, #252
- add finish translation and other minor bugfixes
0.10.4 (2016-04-12)
-------------------
- fix wrapper attribute when using data-isso-require-mail="true", #238
- fix reponse for OPTIONS response on Python 3, #242
0.10.3 (2016-02-24)
-------------------
- follow redirects, #193
0.10.2 (2016-02-21)
-------------------
- fix getAttribute return value
0.10.1 (2016-02-06)
-------------------
- fix empty author, email and website values when writing a comment
0.10 (2016-02-06)
-----------------
- add new configuration section for hash handling.
[hash]
salt = Eech7co8Ohloopo9Ol6baimi
algorithm = pbkdf2
You can customize the salt, choose different hash functions and tweak the
parameters for PBKDF2.
- Python 3.4+ validate TLS connections against the system's CA. Previously no
validation was in place, see PEP-446__ for details.
- add `fenced_code` and `no_intra_emphasis` to default configuration.
Fenced code allows to write code without indentation using `~~~` delimiters
(optionally with language identifier).
Intra emphasis would compile `foo_bar_baz` to foo<em>bar</em>baz. This
behavior is very confusing for users not knowing the Markdown spec in detail.
- new configuration to require an email when submitting comments, #199. Set
[guard]
require-email = true
and use `data-isso-require-email="true"` to enable this feature. Disabled by
default.
- new Bulgarian translation by sahwar, new Swedish translation by Gustav
Näslund – #143, new Vietnamese translation by Đinh Xuân Sâm, new Croatian
translation by streger, new Czech translation by Jan Chren
- fix SMTP setup without credentials, #174
- version pin Misaka to 1.x, html5lib to 0.9999999
.. __: https://www.python.org/dev/peps/pep-0466/
0.9.10 (2015-04-11)
-------------------
- fix regression in SMTP authentication, #174
0.9.9 (2015-03-04)
------------------
- several Python 3.x related bugfixes
- don't lose comment form if the server rejected the POST request, #144
- add localStorage fallback if QUOTA_EXCEEDED_ERR is thrown (e.g. Safari
private browsing)
- add '--empty-id' flag to Disqus import, because Disqus' export sucks
- (re)gain compatibility with Werkzeug 0.8 and really old html5lib versions
available in Debian Squeeze, #170 & #168
- add User-Agent when Isso requests the URL, an alternate way to #151 (add
'X-Isso' when requesting).
0.9.8 (2014-10-08)
------------------
- add compatibility with configparser==3.5.0b1, #128
0.9.7 (2014-09-25)
------------------
- fix SMTP authentication using CRAM-MD5 (incorrect usage of
`smtplib`), #126
0.9.6 (2014-08-18)
------------------
- remember name, email and website in localStorage, #119
- add option to hide voting feature, #115
data-isso-vote="true|false"
- remove email field from JSON responses
This is a quite serious issue. For the identicon, an expensive hash is used
to avoid the leakage of personal information like a real email address. A
`git blame` reveals, the email has been unintentionally exposed since the very
first release of Isso :-/
The testsuite now contains a dedicated test to prevent this error in the
future.
0.9.5 (2014-08-10)
------------------
- prevent no-break space ( ) insertion to enable manual line breaks using
two trailing spaces (as per Markdown convention), #112
- limit request size to 256 kb, #107
Previously unlimited or limited by proxy server). 256 kb is a rough
approximation of the next database schema with comments limited to 65535
characters and additional fields.
- add support for logging to file, #103
[general]
log-file =
- show timestamp when hovering <time>, #104
- fix a regression when editing comments with multiple paragraphs introduced
in 0.9.3 which would HTML escape manually inserted linebreaks.
0.9.4 (2014-07-09)
------------------
- fixed a regression when using Isso and Gevent
0.9.3 (2014-07-09)
------------------
- remove scrollIntoView while expanding further comments if a fragment is used
(e.g. #isso-thread brought you back to the top, unexpectedly)
- implement a custom Markdown renderer to support multi-line code listings. The
extension "fenced_code" is now enabled by default and generates HTML
compatible with Highlight.js__.
- escape HTML entities when editing a comment with raw HTML
- fix CSS for input
- remove isso.css from binary distribution to avoid confusion (it's still there
from the very first release, but modifications do not work)
.. __: http://highlightjs.org/
0.9 (2014-05-29)
----------------
- comment pagination by Srijan Choudhary, #15
Isso can now limit the amount of comments shown by default and add link to
show more. By default, all top-level comments are shown but only 5 nested
comments (per reply). You can override the settings:
isso-data-max-comments-top="N"
isso-data-max-comments-nested="N"
Where N is a number from 0 to infinity ("inf"). If you limit the amount of
shown top level comments, the overall comment count may be incorrect and a
known issue.
You can also configure the amount of comments shown per click (5 by default):
isso-data-reveal-on-click="N"
This feature also required a change in the comment structure. Previously, all
comments are stored tree-like but shown linearly. To ease the implementation
of pagination, the comment tree is now limited to a maximum depth of one.
Jeff Atwood explains, why `discussions are flat by design`__.
.. __: http://blog.codinghorror.com/web-discussions-flat-by-design/
When you upgrade, Isso will automatically normalize the tree and some
information gets lost. All new replies to a comment are now automatically a
direct child of the top-level comment.
- style improvements by William Dorffer, #39, #84 #90 and #91
Isso now longer uses a fat SCSS library, but plain CSS instead. The design is
now responsive and no longer sets global CSS rules.
- experimental WordPress import, #75
Isso should be able to import WXR 1.0-1.2 exports. The import code is based
on two WXR dumps I found (and created) and may not work for you. Please
report any failure.
- avatar changes, #49
You can now configure the client to not show avatars:
data-isso-avatar="false"
Also there is no longer an avatar shown next to the comment box. This is due
to the new CSS and removes two runtime dependencies.
- you may now set a full From header, #87
[smtp]
from = Foo Bar <spam@local>
- SMTP (all caps) is now recognized for notifications, #95
- Isso now ships a small demo site at /demo, #44
- a few bugfixes: Disqus import now anonymizes IP addresses, uWSGI spooling for
Python 3, HTTP-Referer fallback for HTTP-Origin
- remove Django's PBKDF2 implementation in favour of the PBKDF2 function
available in werkzeug 0.9 or higher. If you're still using werkzeug 0.8, Isso
imports passlib__ as fallback (if available).
This release also features a new templating engine Jade__ which replaces
Markup.js__. Jade can compile directly to JavaScript with a tiny runtime module
on the client. Along with the removal of sha1.js and pbkdf2.js and a few build
optimizations, the JS client now weighs only 40kb (12kb gzipped) – 52kb resp.
17kb before.
.. __: https://pypi.python.org/pypi/passlib
.. __: http://jade-lang.com/
.. __: https://github.com/adammark/Markup.js
0.8 (2014-03-28)
----------------
- replace ``<textarea>`` with ``<div contentedtiable="true">`` to remove the
sluggish auto-resize on input feature. If you use a custom CSS, replace
``textarea`` with ``.textarea`` and also set ``white-space: pre``.
- remove superscript extension from Markdown defaults as it may lead to
unexpected behavior for certain smileys such as "^^". To enable the extension,
add
[markup]
options = superscript
allowed-elements = sup
to your configuration.
- comment count requests are now bundled into a single POST request, but the old
API is still there (deprecated though).
- store *session-key* in database (once generated on database creation). That
means links to activate, edit or delete comments are now always valid even
when you restart Isso.
Currently statically set session keys in ``[general]`` are automatically
migrated into the database on startup and you will get a notice that you can
remove this option.
- fix undefined timestamp when client time differs for more than 1 second.
The human-readable "time ago" deltas have been refined to match `Moment.js`_
behavior.
- avatar colors and background can now be customized:
* ``data-isso-avatar-bg="#f0f0f0"`` sets the background color
* ``data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."`` sets possible
avatar colors (up to 8 colors are possible).
- new [markup] section to customize Misaka's Markdown generation (strikethrough,
superscript and autolink enabled by default). Furthermore, you can now allow
certain HTML elemenets and attributes in the generated output, e.g. to enable
images, set
[markup]
allowed-elements = img
allowed-attributes = src
Check docs/configuration/server.rst for more details.
- replace requirejs-domready with a (self-made) HTML5 idiom, #51
.. _Moment.js: http://momentjs.com/docs/#/displaying/fromnow/
0.7 (2014-01-29)
----------------
- fix malicious HTML injection (due to wrong API usage). All unknown/unsafe
HTML tags are now removed from the output (`html5lib` 0.99(9) or later) or
properly escaped (older `html5lib` versions).
See 36d702c and 3a1f92b for more details.
- remove kriskowal/q JS library (promises implementation) in favour of a
self-made 50 LoC implementation to ease packaging (for Debian), #51
- add documentation to display a comment counter, #56 and #57
- SMTP notifications now support STARTTLS and use this transport security
by default, #48 and #58. This also changes the configuration option from
`ssl = [yes|no]` to `security = [none|starttls|ssl]`.
- translation can now be made (and updated) with Transifex_. If you want to
take ownership for a language, contact me on IRC.
- fix french pluralform
- the (by default random) session-key is now shown on application startup
to make different keys per startup more visible
- use `threading.lock` by default for systems without semaphore support
.. _Transifex: https://www.transifex.com/projects/p/isso/
0.6 (2013-12-16)
----------------
Major improvements:
- override thread discovery with data-isso-id="...", #27
To use the same thread for different URLs, you can now add a custom
``data-isso-id="my-id"`` attribute which is used to identify and retrieve
comments (defaults to current URL aka `window.location.pathname`).
- `isso.dispatch` now dispatches multiple websites (= configurations) based on
URL prefixes
- fix a cross-site request forgery vulnerability for comment creation, voting,
editing and deletion, #40
- show modal dialog to confirm comment deletion and activation, #36
- new, comprehensive documentation based on reST + Sphinx:
http://posativ.org/docs (or docs/ in the repository). Also includes an
annotated `example.conf`, #43
- new italian and russian translations
Minor improvements:
- move `isso:application` to `isso.run:application` to avoid uneccessary
initialization in some cases (change module if you use uWSGI or Gunicorn)
- add Date header to email notifications, #42
- check for blank text in new comment, #41
- work around IE10's HTML5 abilities for custom data-attributes
- add support for Gunicorn (and other pre-forking WSGI servers)
0.5 (2013-11-17)
----------------
Major improvements:
- `listen` option replaces `host` and `port` to support UNIX domain sockets, #25
Instead of `host = localhost` and `port = 8080`, use
`listen = http://localhost:8080`. To listen on a UNIX domain socket, replace
`http://` with `unix://`, e.g. `unix:///tmp/isso.sock`.
- new option `notify` (in the general section) is used to choose (one or more)
notification backends (currently only SMTP is available, though). Isso will
no longer automatically use SMTP for notifications if the initial connection
succeeds.
- new options to control the client integration
* ``data-isso-css="false"`` prevents the client from appending the CSS to the
document. Enabled by default.
* ``data-isso-lang="de"`` overrides the useragent's preferred language (de, en
and fr are currently supported).
* ``data-isso-reply-to-self="true"`` should be set, when you allow reply to
own comments (see server configuration for details).
- add support for `gevent <http://www.gevent.org/>`_, a coroutine-based Python
networking library that uses greenlets (lightweight threads). Recommended
WSGI server when not running with uWSGI (unfortunately stable gevent is not
yet able to listen on a UNIX domain socket).
- fix a serious issue with the voters bloomfilter. During an Isso run, the
ip addresses from all commenters accumulated into the voters bloomfilter
for new comments. Thus, previous commenters could no longer vote other
comments. This fixes the rare occurences of #5.
In addition to this fix, the current voters bloomfilter will be re-initialized
if you are using Isso 0.4 or below (this is not necessary, but on the
other hand, the current bloomfilter for each comment is sort-of useless).
- french translation (thanks to @sploinga), #38
- support for multiple sites, part of #34
Minor improvements:
- `ipaddr` is now used as `ipaddress` fallback for Python 2.6 and 2.7, #32
- changed URL to activate and delete comments to `/id/<N:int>/activate` etc.
- import command uses `<link>` tag instead of `<id>` to extract the relative
URL path, #37
- import command now uses `isDeleted` to mark comments as deleted (and
eventually remove stale comments). This seems to affect only a few comments
from a previous WordPress import into Disqus.
- import command lists orphaned comments after import.
- import command now has a ``--dry-run`` option to do no actual operation on
the database.
0.4 (2013-11-05)
----------------
- Isso now handles cross-domain requests and cookies, fixes #24
- Isso for Python 2.x now supports werkzeug>=0.8
- limit email length to 254 to avoid Hash-DDoS
- override Isso API location with ``data-isso="..."`` in the script tag
- override HTML title parsing with a custom ``data-title="..."`` attribute
in ``<div id="isso-thread"></div>``
0.3 (2013-11-01)
----------------
- improve initial comment loading performance in the client
- cache slow REST requests, see #18
- add a SQLite trigger that detects and removes stale threads (= threads,
with all comments being removed) from the database when a comment is
removed.
- PyPi releases now include an uncompressed version of the JavaScript
files -- `embed.dev.js` and `count.dev.js` -- to track down errors.
- use uWSGI's internal locking instead of a self-made shared memory lock
0.2 (2013-10-29)
----------------
- initial PyPi release
| Changelog for Isso
==================
%(version)s (%(date)s)
- Drop support for outdated Python version 3.5
(#808, l33tname)
0.12.6 (2022-03-06)
-------------------
- Serve isso.css separately to avoid ``style-src: unsafe-inline`` CSP and allow
clients to override fetch location (#704, ix5):
data-isso-css-url="https://comments.example.org/css/isso.css"
- New "samesite" option in [server] section to override SameSite header for
cookies. (#700, ix5)
- Fallback for SameSite header depending on whether host is served over https
or http (#700, ix5)
- Have client read out shared settings from server. (#311, pellenilsson)
This affects these settings for which ``data-isso-*`` values will be ignored:
[general]
reply-notifications
gravatar
[guard]
reply-to-self
require-author
require-email
- Improved detection of browser-supplied language preferences (#521)
Isso will now honor the newer ``navigator.languages`` global property
as well as ``navigator.language`` and ``navigator.userLanguage``.
There is a new configuration property ``data-isso-default-lang``
that specifies the language to use (instead of English) when none
of these is available. (The existing ``data-isso-lang`` *overrides*
browser-supplied language preferences.)
- Remove ``ISSO_CORS_ORIGIN`` environ variable, which never worked at all
(#803, ix5)
0.12.5 (2021-03-09)
-------------------
- Don't ignore missing configuration files.
(Jelmer Vernooij)
0.12.4 (2021-02-03)
-------------------
- Require Python >= 3.5, for consistency with werkzeug.
(#698, Stefan Gehn)
- Use npm for package installation.
(#695, Stefan Gehn)
- Use sassc. (Stefan Gehn)
- Cope with broken HTTP clients that require specific casing of
"200 OK". (#646, #347, Konzertheld)
- Add European Portuguese translation. (#692, boturon)
- Various doc updates. (ix5)
- Add Turkish translation. (Özcan Oğuz, #669)
- Drop Python 2 support. (Jelmer Vernooij)
0.12.3 (2020-02-22)
-------------------
- New "flags" option in the [markdown] section to customize Misaka's Markdown
HTML rendering. By default, no flags are set.
[markup]
flags = skip-html, escape, hard-wrap
Check docs/configuration/server.rst for more details. #616
* Fix compatibility with newer versions of werkzeug. #614
* Add Python 3.8 support. #600, #615
* New 'latest' endpoint to serve latest comments. #556
* include admin.js in Python Package. #606
* Add a approve-if-email-previously-approved setting.
* Fall back to author names in gravatars (#482)
* Make Isso compatible with Content Security Policies without `script-src 'unsafe-inline'`. #597
* Set subject for notification about new comment, subject should not be empty. #589
* Fix rendering of disabled.html for 'Sub URI' sites.
* contrib: Add Blogger importer tool. #529
* Return 200 with empty array when there are no comments. #301
* Translation updates for Polish, Slovak, Occitan.
* Redirect to comment after moderation. #358
0.12.2 (2019-01-21)
-------------------
- Revert use of labels instead of placeholders, since it breaks
mail notifications. #524
0.12.1 (2019-01-19)
-------------------
- Revert fix for duplicate slashes, as it prevents isso from
starting in some cases. #523
0.12.0 (2019-01-18)
-------------------
- Fix compatibility with new XML API.
- Don't enable admin interface with default password by default. #491
- Add support and documentation for "generic" imports.
- Remove potential duplicate slashes in URLs from
email links. #420
- Add data-isso-reply-notifications to attributes in configuration.
- Use default IP in imports if none is found. Fixes imports of some comments.
- embed: fix feed link creation on older browsers.
- Properly handle to field in mail notifications when using uWSGI spooler
- css: fix vertical alignment of notification checkbox
0.11.1 (2018-11-03)
-------------------
- Include pre-built minified JavaScript and CSS.
0.11.0 (2018-11-03)
-------------------
Bugs & features:
- Fix link in moderation mails if isso is setup on a sub-url (e.g. domain.tld/comments/)
- Add reply notifications
- Add admin interface
- Add links highlighting in comments
- Add apidoc
- Add rc.d script for FreeBSD
- Add the possibility to set CORS Origin through ISSO_CORS_ORIGIN environ variable
- Add preview button
- Add Atom feed at /feed?uri={thread-id}
- Add optionnal gravatar support
- Add nofollow noopener on links inside comments
- Add Dockerfile
- Upgraded to Misaka 2
- Some tests/travis/documentation improvements and fixes + pep8
Translations:
- Fix Chinese translation & typo in CJK
- Add Danish translation
- Add Hungarian translation
- Add Persian translation
- Improvement on german translation
0.10.6 (2016-09-22)
-------------------
- fix missing configuration field
0.10.5 (2016-09-20)
-------------------
- add support for different vote levels, #260
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg.
`"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given
one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg.
put a star on popular comments).
- add new post preview API endpoint, #254
- add an option for mandatory author, #257
- clients can now use `data-title` to get the HTML title for a new page, #252
- add finish translation and other minor bugfixes
0.10.4 (2016-04-12)
-------------------
- fix wrapper attribute when using data-isso-require-mail="true", #238
- fix reponse for OPTIONS response on Python 3, #242
0.10.3 (2016-02-24)
-------------------
- follow redirects, #193
0.10.2 (2016-02-21)
-------------------
- fix getAttribute return value
0.10.1 (2016-02-06)
-------------------
- fix empty author, email and website values when writing a comment
0.10 (2016-02-06)
-----------------
- add new configuration section for hash handling.
[hash]
salt = Eech7co8Ohloopo9Ol6baimi
algorithm = pbkdf2
You can customize the salt, choose different hash functions and tweak the
parameters for PBKDF2.
- Python 3.4+ validate TLS connections against the system's CA. Previously no
validation was in place, see PEP-446__ for details.
- add `fenced_code` and `no_intra_emphasis` to default configuration.
Fenced code allows to write code without indentation using `~~~` delimiters
(optionally with language identifier).
Intra emphasis would compile `foo_bar_baz` to foo<em>bar</em>baz. This
behavior is very confusing for users not knowing the Markdown spec in detail.
- new configuration to require an email when submitting comments, #199. Set
[guard]
require-email = true
and use `data-isso-require-email="true"` to enable this feature. Disabled by
default.
- new Bulgarian translation by sahwar, new Swedish translation by Gustav
Näslund – #143, new Vietnamese translation by Đinh Xuân Sâm, new Croatian
translation by streger, new Czech translation by Jan Chren
- fix SMTP setup without credentials, #174
- version pin Misaka to 1.x, html5lib to 0.9999999
.. __: https://www.python.org/dev/peps/pep-0466/
0.9.10 (2015-04-11)
-------------------
- fix regression in SMTP authentication, #174
0.9.9 (2015-03-04)
------------------
- several Python 3.x related bugfixes
- don't lose comment form if the server rejected the POST request, #144
- add localStorage fallback if QUOTA_EXCEEDED_ERR is thrown (e.g. Safari
private browsing)
- add '--empty-id' flag to Disqus import, because Disqus' export sucks
- (re)gain compatibility with Werkzeug 0.8 and really old html5lib versions
available in Debian Squeeze, #170 & #168
- add User-Agent when Isso requests the URL, an alternate way to #151 (add
'X-Isso' when requesting).
0.9.8 (2014-10-08)
------------------
- add compatibility with configparser==3.5.0b1, #128
0.9.7 (2014-09-25)
------------------
- fix SMTP authentication using CRAM-MD5 (incorrect usage of
`smtplib`), #126
0.9.6 (2014-08-18)
------------------
- remember name, email and website in localStorage, #119
- add option to hide voting feature, #115
data-isso-vote="true|false"
- remove email field from JSON responses
This is a quite serious issue. For the identicon, an expensive hash is used
to avoid the leakage of personal information like a real email address. A
`git blame` reveals, the email has been unintentionally exposed since the very
first release of Isso :-/
The testsuite now contains a dedicated test to prevent this error in the
future.
0.9.5 (2014-08-10)
------------------
- prevent no-break space ( ) insertion to enable manual line breaks using
two trailing spaces (as per Markdown convention), #112
- limit request size to 256 kb, #107
Previously unlimited or limited by proxy server). 256 kb is a rough
approximation of the next database schema with comments limited to 65535
characters and additional fields.
- add support for logging to file, #103
[general]
log-file =
- show timestamp when hovering <time>, #104
- fix a regression when editing comments with multiple paragraphs introduced
in 0.9.3 which would HTML escape manually inserted linebreaks.
0.9.4 (2014-07-09)
------------------
- fixed a regression when using Isso and Gevent
0.9.3 (2014-07-09)
------------------
- remove scrollIntoView while expanding further comments if a fragment is used
(e.g. #isso-thread brought you back to the top, unexpectedly)
- implement a custom Markdown renderer to support multi-line code listings. The
extension "fenced_code" is now enabled by default and generates HTML
compatible with Highlight.js__.
- escape HTML entities when editing a comment with raw HTML
- fix CSS for input
- remove isso.css from binary distribution to avoid confusion (it's still there
from the very first release, but modifications do not work)
.. __: http://highlightjs.org/
0.9 (2014-05-29)
----------------
- comment pagination by Srijan Choudhary, #15
Isso can now limit the amount of comments shown by default and add link to
show more. By default, all top-level comments are shown but only 5 nested
comments (per reply). You can override the settings:
isso-data-max-comments-top="N"
isso-data-max-comments-nested="N"
Where N is a number from 0 to infinity ("inf"). If you limit the amount of
shown top level comments, the overall comment count may be incorrect and a
known issue.
You can also configure the amount of comments shown per click (5 by default):
isso-data-reveal-on-click="N"
This feature also required a change in the comment structure. Previously, all
comments are stored tree-like but shown linearly. To ease the implementation
of pagination, the comment tree is now limited to a maximum depth of one.
Jeff Atwood explains, why `discussions are flat by design`__.
.. __: http://blog.codinghorror.com/web-discussions-flat-by-design/
When you upgrade, Isso will automatically normalize the tree and some
information gets lost. All new replies to a comment are now automatically a
direct child of the top-level comment.
- style improvements by William Dorffer, #39, #84 #90 and #91
Isso now longer uses a fat SCSS library, but plain CSS instead. The design is
now responsive and no longer sets global CSS rules.
- experimental WordPress import, #75
Isso should be able to import WXR 1.0-1.2 exports. The import code is based
on two WXR dumps I found (and created) and may not work for you. Please
report any failure.
- avatar changes, #49
You can now configure the client to not show avatars:
data-isso-avatar="false"
Also there is no longer an avatar shown next to the comment box. This is due
to the new CSS and removes two runtime dependencies.
- you may now set a full From header, #87
[smtp]
from = Foo Bar <spam@local>
- SMTP (all caps) is now recognized for notifications, #95
- Isso now ships a small demo site at /demo, #44
- a few bugfixes: Disqus import now anonymizes IP addresses, uWSGI spooling for
Python 3, HTTP-Referer fallback for HTTP-Origin
- remove Django's PBKDF2 implementation in favour of the PBKDF2 function
available in werkzeug 0.9 or higher. If you're still using werkzeug 0.8, Isso
imports passlib__ as fallback (if available).
This release also features a new templating engine Jade__ which replaces
Markup.js__. Jade can compile directly to JavaScript with a tiny runtime module
on the client. Along with the removal of sha1.js and pbkdf2.js and a few build
optimizations, the JS client now weighs only 40kb (12kb gzipped) – 52kb resp.
17kb before.
.. __: https://pypi.python.org/pypi/passlib
.. __: http://jade-lang.com/
.. __: https://github.com/adammark/Markup.js
0.8 (2014-03-28)
----------------
- replace ``<textarea>`` with ``<div contentedtiable="true">`` to remove the
sluggish auto-resize on input feature. If you use a custom CSS, replace
``textarea`` with ``.textarea`` and also set ``white-space: pre``.
- remove superscript extension from Markdown defaults as it may lead to
unexpected behavior for certain smileys such as "^^". To enable the extension,
add
[markup]
options = superscript
allowed-elements = sup
to your configuration.
- comment count requests are now bundled into a single POST request, but the old
API is still there (deprecated though).
- store *session-key* in database (once generated on database creation). That
means links to activate, edit or delete comments are now always valid even
when you restart Isso.
Currently statically set session keys in ``[general]`` are automatically
migrated into the database on startup and you will get a notice that you can
remove this option.
- fix undefined timestamp when client time differs for more than 1 second.
The human-readable "time ago" deltas have been refined to match `Moment.js`_
behavior.
- avatar colors and background can now be customized:
* ``data-isso-avatar-bg="#f0f0f0"`` sets the background color
* ``data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."`` sets possible
avatar colors (up to 8 colors are possible).
- new [markup] section to customize Misaka's Markdown generation (strikethrough,
superscript and autolink enabled by default). Furthermore, you can now allow
certain HTML elemenets and attributes in the generated output, e.g. to enable
images, set
[markup]
allowed-elements = img
allowed-attributes = src
Check docs/configuration/server.rst for more details.
- replace requirejs-domready with a (self-made) HTML5 idiom, #51
.. _Moment.js: http://momentjs.com/docs/#/displaying/fromnow/
0.7 (2014-01-29)
----------------
- fix malicious HTML injection (due to wrong API usage). All unknown/unsafe
HTML tags are now removed from the output (`html5lib` 0.99(9) or later) or
properly escaped (older `html5lib` versions).
See 36d702c and 3a1f92b for more details.
- remove kriskowal/q JS library (promises implementation) in favour of a
self-made 50 LoC implementation to ease packaging (for Debian), #51
- add documentation to display a comment counter, #56 and #57
- SMTP notifications now support STARTTLS and use this transport security
by default, #48 and #58. This also changes the configuration option from
`ssl = [yes|no]` to `security = [none|starttls|ssl]`.
- translation can now be made (and updated) with Transifex_. If you want to
take ownership for a language, contact me on IRC.
- fix french pluralform
- the (by default random) session-key is now shown on application startup
to make different keys per startup more visible
- use `threading.lock` by default for systems without semaphore support
.. _Transifex: https://www.transifex.com/projects/p/isso/
0.6 (2013-12-16)
----------------
Major improvements:
- override thread discovery with data-isso-id="...", #27
To use the same thread for different URLs, you can now add a custom
``data-isso-id="my-id"`` attribute which is used to identify and retrieve
comments (defaults to current URL aka `window.location.pathname`).
- `isso.dispatch` now dispatches multiple websites (= configurations) based on
URL prefixes
- fix a cross-site request forgery vulnerability for comment creation, voting,
editing and deletion, #40
- show modal dialog to confirm comment deletion and activation, #36
- new, comprehensive documentation based on reST + Sphinx:
http://posativ.org/docs (or docs/ in the repository). Also includes an
annotated `example.conf`, #43
- new italian and russian translations
Minor improvements:
- move `isso:application` to `isso.run:application` to avoid uneccessary
initialization in some cases (change module if you use uWSGI or Gunicorn)
- add Date header to email notifications, #42
- check for blank text in new comment, #41
- work around IE10's HTML5 abilities for custom data-attributes
- add support for Gunicorn (and other pre-forking WSGI servers)
0.5 (2013-11-17)
----------------
Major improvements:
- `listen` option replaces `host` and `port` to support UNIX domain sockets, #25
Instead of `host = localhost` and `port = 8080`, use
`listen = http://localhost:8080`. To listen on a UNIX domain socket, replace
`http://` with `unix://`, e.g. `unix:///tmp/isso.sock`.
- new option `notify` (in the general section) is used to choose (one or more)
notification backends (currently only SMTP is available, though). Isso will
no longer automatically use SMTP for notifications if the initial connection
succeeds.
- new options to control the client integration
* ``data-isso-css="false"`` prevents the client from appending the CSS to the
document. Enabled by default.
* ``data-isso-lang="de"`` overrides the useragent's preferred language (de, en
and fr are currently supported).
* ``data-isso-reply-to-self="true"`` should be set, when you allow reply to
own comments (see server configuration for details).
- add support for `gevent <http://www.gevent.org/>`_, a coroutine-based Python
networking library that uses greenlets (lightweight threads). Recommended
WSGI server when not running with uWSGI (unfortunately stable gevent is not
yet able to listen on a UNIX domain socket).
- fix a serious issue with the voters bloomfilter. During an Isso run, the
ip addresses from all commenters accumulated into the voters bloomfilter
for new comments. Thus, previous commenters could no longer vote other
comments. This fixes the rare occurences of #5.
In addition to this fix, the current voters bloomfilter will be re-initialized
if you are using Isso 0.4 or below (this is not necessary, but on the
other hand, the current bloomfilter for each comment is sort-of useless).
- french translation (thanks to @sploinga), #38
- support for multiple sites, part of #34
Minor improvements:
- `ipaddr` is now used as `ipaddress` fallback for Python 2.6 and 2.7, #32
- changed URL to activate and delete comments to `/id/<N:int>/activate` etc.
- import command uses `<link>` tag instead of `<id>` to extract the relative
URL path, #37
- import command now uses `isDeleted` to mark comments as deleted (and
eventually remove stale comments). This seems to affect only a few comments
from a previous WordPress import into Disqus.
- import command lists orphaned comments after import.
- import command now has a ``--dry-run`` option to do no actual operation on
the database.
0.4 (2013-11-05)
----------------
- Isso now handles cross-domain requests and cookies, fixes #24
- Isso for Python 2.x now supports werkzeug>=0.8
- limit email length to 254 to avoid Hash-DDoS
- override Isso API location with ``data-isso="..."`` in the script tag
- override HTML title parsing with a custom ``data-title="..."`` attribute
in ``<div id="isso-thread"></div>``
0.3 (2013-11-01)
----------------
- improve initial comment loading performance in the client
- cache slow REST requests, see #18
- add a SQLite trigger that detects and removes stale threads (= threads,
with all comments being removed) from the database when a comment is
removed.
- PyPi releases now include an uncompressed version of the JavaScript
files -- `embed.dev.js` and `count.dev.js` -- to track down errors.
- use uWSGI's internal locking instead of a self-made shared memory lock
0.2 (2013-10-29)
----------------
- initial PyPi release
| fliiiix | 8c306f45a24b6996d2fcc44d6564a552021ed03d | 79a774699cfb994b5098428bad154699e2d361cf | outdated | ix5 | 60 |
posativ/isso | 808 | setup.py: drop python3.5 support | Since not tests are run for 3.5 drop support
with the next release.
Also Python 3.5 has reached end-of-life on 5-Sep-2020.
Python 3.5.10 is the final release of 3.5.
https://www.python.org/downloads/release/python-3510/ | null | 2022-03-06 14:09:53+00:00 | 2022-03-27 21:45:09+00:00 | CHANGES.rst | Changelog for Isso
==================
%(version)s (%(date)s)
0.12.6 (2022-03-06)
-------------------
- Serve isso.css separately to avoid ``style-src: unsafe-inline`` CSP and allow
clients to override fetch location (#704, ix5):
data-isso-css-url="https://comments.example.org/css/isso.css"
- New "samesite" option in [server] section to override SameSite header for
cookies. (#700, ix5)
- Fallback for SameSite header depending on whether host is served over https
or http (#700, ix5)
- Have client read out shared settings from server. (#311, pellenilsson)
This affects these settings for which ``data-isso-*`` values will be ignored:
[general]
reply-notifications
gravatar
[guard]
reply-to-self
require-author
require-email
- Improved detection of browser-supplied language preferences (#521)
Isso will now honor the newer ``navigator.languages`` global property
as well as ``navigator.language`` and ``navigator.userLanguage``.
There is a new configuration property ``data-isso-default-lang``
that specifies the language to use (instead of English) when none
of these is available. (The existing ``data-isso-lang`` *overrides*
browser-supplied language preferences.)
- Remove ``ISSO_CORS_ORIGIN`` environ variable, which never worked at all
(#803, ix5)
0.12.5 (2021-03-09)
-------------------
- Don't ignore missing configuration files.
(Jelmer Vernooij)
0.12.4 (2021-02-03)
-------------------
- Require Python >= 3.5, for consistency with werkzeug.
(#698, Stefan Gehn)
- Use npm for package installation.
(#695, Stefan Gehn)
- Use sassc. (Stefan Gehn)
- Cope with broken HTTP clients that require specific casing of
"200 OK". (#646, #347, Konzertheld)
- Add European Portuguese translation. (#692, boturon)
- Various doc updates. (ix5)
- Add Turkish translation. (Özcan Oğuz, #669)
- Drop Python 2 support. (Jelmer Vernooij)
0.12.3 (2020-02-22)
-------------------
- New "flags" option in the [markdown] section to customize Misaka's Markdown
HTML rendering. By default, no flags are set.
[markup]
flags = skip-html, escape, hard-wrap
Check docs/configuration/server.rst for more details. #616
* Fix compatibility with newer versions of werkzeug. #614
* Add Python 3.8 support. #600, #615
* New 'latest' endpoint to serve latest comments. #556
* include admin.js in Python Package. #606
* Add a approve-if-email-previously-approved setting.
* Fall back to author names in gravatars (#482)
* Make Isso compatible with Content Security Policies without `script-src 'unsafe-inline'`. #597
* Set subject for notification about new comment, subject should not be empty. #589
* Fix rendering of disabled.html for 'Sub URI' sites.
* contrib: Add Blogger importer tool. #529
* Return 200 with empty array when there are no comments. #301
* Translation updates for Polish, Slovak, Occitan.
* Redirect to comment after moderation. #358
0.12.2 (2019-01-21)
-------------------
- Revert use of labels instead of placeholders, since it breaks
mail notifications. #524
0.12.1 (2019-01-19)
-------------------
- Revert fix for duplicate slashes, as it prevents isso from
starting in some cases. #523
0.12.0 (2019-01-18)
-------------------
- Fix compatibility with new XML API.
- Don't enable admin interface with default password by default. #491
- Add support and documentation for "generic" imports.
- Remove potential duplicate slashes in URLs from
email links. #420
- Add data-isso-reply-notifications to attributes in configuration.
- Use default IP in imports if none is found. Fixes imports of some comments.
- embed: fix feed link creation on older browsers.
- Properly handle to field in mail notifications when using uWSGI spooler
- css: fix vertical alignment of notification checkbox
0.11.1 (2018-11-03)
-------------------
- Include pre-built minified JavaScript and CSS.
0.11.0 (2018-11-03)
-------------------
Bugs & features:
- Fix link in moderation mails if isso is setup on a sub-url (e.g. domain.tld/comments/)
- Add reply notifications
- Add admin interface
- Add links highlighting in comments
- Add apidoc
- Add rc.d script for FreeBSD
- Add the possibility to set CORS Origin through ISSO_CORS_ORIGIN environ variable
- Add preview button
- Add Atom feed at /feed?uri={thread-id}
- Add optionnal gravatar support
- Add nofollow noopener on links inside comments
- Add Dockerfile
- Upgraded to Misaka 2
- Some tests/travis/documentation improvements and fixes + pep8
Translations:
- Fix Chinese translation & typo in CJK
- Add Danish translation
- Add Hungarian translation
- Add Persian translation
- Improvement on german translation
0.10.6 (2016-09-22)
-------------------
- fix missing configuration field
0.10.5 (2016-09-20)
-------------------
- add support for different vote levels, #260
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg.
`"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given
one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg.
put a star on popular comments).
- add new post preview API endpoint, #254
- add an option for mandatory author, #257
- clients can now use `data-title` to get the HTML title for a new page, #252
- add finish translation and other minor bugfixes
0.10.4 (2016-04-12)
-------------------
- fix wrapper attribute when using data-isso-require-mail="true", #238
- fix reponse for OPTIONS response on Python 3, #242
0.10.3 (2016-02-24)
-------------------
- follow redirects, #193
0.10.2 (2016-02-21)
-------------------
- fix getAttribute return value
0.10.1 (2016-02-06)
-------------------
- fix empty author, email and website values when writing a comment
0.10 (2016-02-06)
-----------------
- add new configuration section for hash handling.
[hash]
salt = Eech7co8Ohloopo9Ol6baimi
algorithm = pbkdf2
You can customize the salt, choose different hash functions and tweak the
parameters for PBKDF2.
- Python 3.4+ validate TLS connections against the system's CA. Previously no
validation was in place, see PEP-446__ for details.
- add `fenced_code` and `no_intra_emphasis` to default configuration.
Fenced code allows to write code without indentation using `~~~` delimiters
(optionally with language identifier).
Intra emphasis would compile `foo_bar_baz` to foo<em>bar</em>baz. This
behavior is very confusing for users not knowing the Markdown spec in detail.
- new configuration to require an email when submitting comments, #199. Set
[guard]
require-email = true
and use `data-isso-require-email="true"` to enable this feature. Disabled by
default.
- new Bulgarian translation by sahwar, new Swedish translation by Gustav
Näslund – #143, new Vietnamese translation by Đinh Xuân Sâm, new Croatian
translation by streger, new Czech translation by Jan Chren
- fix SMTP setup without credentials, #174
- version pin Misaka to 1.x, html5lib to 0.9999999
.. __: https://www.python.org/dev/peps/pep-0466/
0.9.10 (2015-04-11)
-------------------
- fix regression in SMTP authentication, #174
0.9.9 (2015-03-04)
------------------
- several Python 3.x related bugfixes
- don't lose comment form if the server rejected the POST request, #144
- add localStorage fallback if QUOTA_EXCEEDED_ERR is thrown (e.g. Safari
private browsing)
- add '--empty-id' flag to Disqus import, because Disqus' export sucks
- (re)gain compatibility with Werkzeug 0.8 and really old html5lib versions
available in Debian Squeeze, #170 & #168
- add User-Agent when Isso requests the URL, an alternate way to #151 (add
'X-Isso' when requesting).
0.9.8 (2014-10-08)
------------------
- add compatibility with configparser==3.5.0b1, #128
0.9.7 (2014-09-25)
------------------
- fix SMTP authentication using CRAM-MD5 (incorrect usage of
`smtplib`), #126
0.9.6 (2014-08-18)
------------------
- remember name, email and website in localStorage, #119
- add option to hide voting feature, #115
data-isso-vote="true|false"
- remove email field from JSON responses
This is a quite serious issue. For the identicon, an expensive hash is used
to avoid the leakage of personal information like a real email address. A
`git blame` reveals, the email has been unintentionally exposed since the very
first release of Isso :-/
The testsuite now contains a dedicated test to prevent this error in the
future.
0.9.5 (2014-08-10)
------------------
- prevent no-break space ( ) insertion to enable manual line breaks using
two trailing spaces (as per Markdown convention), #112
- limit request size to 256 kb, #107
Previously unlimited or limited by proxy server). 256 kb is a rough
approximation of the next database schema with comments limited to 65535
characters and additional fields.
- add support for logging to file, #103
[general]
log-file =
- show timestamp when hovering <time>, #104
- fix a regression when editing comments with multiple paragraphs introduced
in 0.9.3 which would HTML escape manually inserted linebreaks.
0.9.4 (2014-07-09)
------------------
- fixed a regression when using Isso and Gevent
0.9.3 (2014-07-09)
------------------
- remove scrollIntoView while expanding further comments if a fragment is used
(e.g. #isso-thread brought you back to the top, unexpectedly)
- implement a custom Markdown renderer to support multi-line code listings. The
extension "fenced_code" is now enabled by default and generates HTML
compatible with Highlight.js__.
- escape HTML entities when editing a comment with raw HTML
- fix CSS for input
- remove isso.css from binary distribution to avoid confusion (it's still there
from the very first release, but modifications do not work)
.. __: http://highlightjs.org/
0.9 (2014-05-29)
----------------
- comment pagination by Srijan Choudhary, #15
Isso can now limit the amount of comments shown by default and add link to
show more. By default, all top-level comments are shown but only 5 nested
comments (per reply). You can override the settings:
isso-data-max-comments-top="N"
isso-data-max-comments-nested="N"
Where N is a number from 0 to infinity ("inf"). If you limit the amount of
shown top level comments, the overall comment count may be incorrect and a
known issue.
You can also configure the amount of comments shown per click (5 by default):
isso-data-reveal-on-click="N"
This feature also required a change in the comment structure. Previously, all
comments are stored tree-like but shown linearly. To ease the implementation
of pagination, the comment tree is now limited to a maximum depth of one.
Jeff Atwood explains, why `discussions are flat by design`__.
.. __: http://blog.codinghorror.com/web-discussions-flat-by-design/
When you upgrade, Isso will automatically normalize the tree and some
information gets lost. All new replies to a comment are now automatically a
direct child of the top-level comment.
- style improvements by William Dorffer, #39, #84 #90 and #91
Isso now longer uses a fat SCSS library, but plain CSS instead. The design is
now responsive and no longer sets global CSS rules.
- experimental WordPress import, #75
Isso should be able to import WXR 1.0-1.2 exports. The import code is based
on two WXR dumps I found (and created) and may not work for you. Please
report any failure.
- avatar changes, #49
You can now configure the client to not show avatars:
data-isso-avatar="false"
Also there is no longer an avatar shown next to the comment box. This is due
to the new CSS and removes two runtime dependencies.
- you may now set a full From header, #87
[smtp]
from = Foo Bar <spam@local>
- SMTP (all caps) is now recognized for notifications, #95
- Isso now ships a small demo site at /demo, #44
- a few bugfixes: Disqus import now anonymizes IP addresses, uWSGI spooling for
Python 3, HTTP-Referer fallback for HTTP-Origin
- remove Django's PBKDF2 implementation in favour of the PBKDF2 function
available in werkzeug 0.9 or higher. If you're still using werkzeug 0.8, Isso
imports passlib__ as fallback (if available).
This release also features a new templating engine Jade__ which replaces
Markup.js__. Jade can compile directly to JavaScript with a tiny runtime module
on the client. Along with the removal of sha1.js and pbkdf2.js and a few build
optimizations, the JS client now weighs only 40kb (12kb gzipped) – 52kb resp.
17kb before.
.. __: https://pypi.python.org/pypi/passlib
.. __: http://jade-lang.com/
.. __: https://github.com/adammark/Markup.js
0.8 (2014-03-28)
----------------
- replace ``<textarea>`` with ``<div contentedtiable="true">`` to remove the
sluggish auto-resize on input feature. If you use a custom CSS, replace
``textarea`` with ``.textarea`` and also set ``white-space: pre``.
- remove superscript extension from Markdown defaults as it may lead to
unexpected behavior for certain smileys such as "^^". To enable the extension,
add
[markup]
options = superscript
allowed-elements = sup
to your configuration.
- comment count requests are now bundled into a single POST request, but the old
API is still there (deprecated though).
- store *session-key* in database (once generated on database creation). That
means links to activate, edit or delete comments are now always valid even
when you restart Isso.
Currently statically set session keys in ``[general]`` are automatically
migrated into the database on startup and you will get a notice that you can
remove this option.
- fix undefined timestamp when client time differs for more than 1 second.
The human-readable "time ago" deltas have been refined to match `Moment.js`_
behavior.
- avatar colors and background can now be customized:
* ``data-isso-avatar-bg="#f0f0f0"`` sets the background color
* ``data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."`` sets possible
avatar colors (up to 8 colors are possible).
- new [markup] section to customize Misaka's Markdown generation (strikethrough,
superscript and autolink enabled by default). Furthermore, you can now allow
certain HTML elemenets and attributes in the generated output, e.g. to enable
images, set
[markup]
allowed-elements = img
allowed-attributes = src
Check docs/configuration/server.rst for more details.
- replace requirejs-domready with a (self-made) HTML5 idiom, #51
.. _Moment.js: http://momentjs.com/docs/#/displaying/fromnow/
0.7 (2014-01-29)
----------------
- fix malicious HTML injection (due to wrong API usage). All unknown/unsafe
HTML tags are now removed from the output (`html5lib` 0.99(9) or later) or
properly escaped (older `html5lib` versions).
See 36d702c and 3a1f92b for more details.
- remove kriskowal/q JS library (promises implementation) in favour of a
self-made 50 LoC implementation to ease packaging (for Debian), #51
- add documentation to display a comment counter, #56 and #57
- SMTP notifications now support STARTTLS and use this transport security
by default, #48 and #58. This also changes the configuration option from
`ssl = [yes|no]` to `security = [none|starttls|ssl]`.
- translation can now be made (and updated) with Transifex_. If you want to
take ownership for a language, contact me on IRC.
- fix french pluralform
- the (by default random) session-key is now shown on application startup
to make different keys per startup more visible
- use `threading.lock` by default for systems without semaphore support
.. _Transifex: https://www.transifex.com/projects/p/isso/
0.6 (2013-12-16)
----------------
Major improvements:
- override thread discovery with data-isso-id="...", #27
To use the same thread for different URLs, you can now add a custom
``data-isso-id="my-id"`` attribute which is used to identify and retrieve
comments (defaults to current URL aka `window.location.pathname`).
- `isso.dispatch` now dispatches multiple websites (= configurations) based on
URL prefixes
- fix a cross-site request forgery vulnerability for comment creation, voting,
editing and deletion, #40
- show modal dialog to confirm comment deletion and activation, #36
- new, comprehensive documentation based on reST + Sphinx:
http://posativ.org/docs (or docs/ in the repository). Also includes an
annotated `example.conf`, #43
- new italian and russian translations
Minor improvements:
- move `isso:application` to `isso.run:application` to avoid uneccessary
initialization in some cases (change module if you use uWSGI or Gunicorn)
- add Date header to email notifications, #42
- check for blank text in new comment, #41
- work around IE10's HTML5 abilities for custom data-attributes
- add support for Gunicorn (and other pre-forking WSGI servers)
0.5 (2013-11-17)
----------------
Major improvements:
- `listen` option replaces `host` and `port` to support UNIX domain sockets, #25
Instead of `host = localhost` and `port = 8080`, use
`listen = http://localhost:8080`. To listen on a UNIX domain socket, replace
`http://` with `unix://`, e.g. `unix:///tmp/isso.sock`.
- new option `notify` (in the general section) is used to choose (one or more)
notification backends (currently only SMTP is available, though). Isso will
no longer automatically use SMTP for notifications if the initial connection
succeeds.
- new options to control the client integration
* ``data-isso-css="false"`` prevents the client from appending the CSS to the
document. Enabled by default.
* ``data-isso-lang="de"`` overrides the useragent's preferred language (de, en
and fr are currently supported).
* ``data-isso-reply-to-self="true"`` should be set, when you allow reply to
own comments (see server configuration for details).
- add support for `gevent <http://www.gevent.org/>`_, a coroutine-based Python
networking library that uses greenlets (lightweight threads). Recommended
WSGI server when not running with uWSGI (unfortunately stable gevent is not
yet able to listen on a UNIX domain socket).
- fix a serious issue with the voters bloomfilter. During an Isso run, the
ip addresses from all commenters accumulated into the voters bloomfilter
for new comments. Thus, previous commenters could no longer vote other
comments. This fixes the rare occurences of #5.
In addition to this fix, the current voters bloomfilter will be re-initialized
if you are using Isso 0.4 or below (this is not necessary, but on the
other hand, the current bloomfilter for each comment is sort-of useless).
- french translation (thanks to @sploinga), #38
- support for multiple sites, part of #34
Minor improvements:
- `ipaddr` is now used as `ipaddress` fallback for Python 2.6 and 2.7, #32
- changed URL to activate and delete comments to `/id/<N:int>/activate` etc.
- import command uses `<link>` tag instead of `<id>` to extract the relative
URL path, #37
- import command now uses `isDeleted` to mark comments as deleted (and
eventually remove stale comments). This seems to affect only a few comments
from a previous WordPress import into Disqus.
- import command lists orphaned comments after import.
- import command now has a ``--dry-run`` option to do no actual operation on
the database.
0.4 (2013-11-05)
----------------
- Isso now handles cross-domain requests and cookies, fixes #24
- Isso for Python 2.x now supports werkzeug>=0.8
- limit email length to 254 to avoid Hash-DDoS
- override Isso API location with ``data-isso="..."`` in the script tag
- override HTML title parsing with a custom ``data-title="..."`` attribute
in ``<div id="isso-thread"></div>``
0.3 (2013-11-01)
----------------
- improve initial comment loading performance in the client
- cache slow REST requests, see #18
- add a SQLite trigger that detects and removes stale threads (= threads,
with all comments being removed) from the database when a comment is
removed.
- PyPi releases now include an uncompressed version of the JavaScript
files -- `embed.dev.js` and `count.dev.js` -- to track down errors.
- use uWSGI's internal locking instead of a self-made shared memory lock
0.2 (2013-10-29)
----------------
- initial PyPi release
| Changelog for Isso
==================
%(version)s (%(date)s)
- Drop support for outdated Python version 3.5
(#808, l33tname)
0.12.6 (2022-03-06)
-------------------
- Serve isso.css separately to avoid ``style-src: unsafe-inline`` CSP and allow
clients to override fetch location (#704, ix5):
data-isso-css-url="https://comments.example.org/css/isso.css"
- New "samesite" option in [server] section to override SameSite header for
cookies. (#700, ix5)
- Fallback for SameSite header depending on whether host is served over https
or http (#700, ix5)
- Have client read out shared settings from server. (#311, pellenilsson)
This affects these settings for which ``data-isso-*`` values will be ignored:
[general]
reply-notifications
gravatar
[guard]
reply-to-self
require-author
require-email
- Improved detection of browser-supplied language preferences (#521)
Isso will now honor the newer ``navigator.languages`` global property
as well as ``navigator.language`` and ``navigator.userLanguage``.
There is a new configuration property ``data-isso-default-lang``
that specifies the language to use (instead of English) when none
of these is available. (The existing ``data-isso-lang`` *overrides*
browser-supplied language preferences.)
- Remove ``ISSO_CORS_ORIGIN`` environ variable, which never worked at all
(#803, ix5)
0.12.5 (2021-03-09)
-------------------
- Don't ignore missing configuration files.
(Jelmer Vernooij)
0.12.4 (2021-02-03)
-------------------
- Require Python >= 3.5, for consistency with werkzeug.
(#698, Stefan Gehn)
- Use npm for package installation.
(#695, Stefan Gehn)
- Use sassc. (Stefan Gehn)
- Cope with broken HTTP clients that require specific casing of
"200 OK". (#646, #347, Konzertheld)
- Add European Portuguese translation. (#692, boturon)
- Various doc updates. (ix5)
- Add Turkish translation. (Özcan Oğuz, #669)
- Drop Python 2 support. (Jelmer Vernooij)
0.12.3 (2020-02-22)
-------------------
- New "flags" option in the [markdown] section to customize Misaka's Markdown
HTML rendering. By default, no flags are set.
[markup]
flags = skip-html, escape, hard-wrap
Check docs/configuration/server.rst for more details. #616
* Fix compatibility with newer versions of werkzeug. #614
* Add Python 3.8 support. #600, #615
* New 'latest' endpoint to serve latest comments. #556
* include admin.js in Python Package. #606
* Add a approve-if-email-previously-approved setting.
* Fall back to author names in gravatars (#482)
* Make Isso compatible with Content Security Policies without `script-src 'unsafe-inline'`. #597
* Set subject for notification about new comment, subject should not be empty. #589
* Fix rendering of disabled.html for 'Sub URI' sites.
* contrib: Add Blogger importer tool. #529
* Return 200 with empty array when there are no comments. #301
* Translation updates for Polish, Slovak, Occitan.
* Redirect to comment after moderation. #358
0.12.2 (2019-01-21)
-------------------
- Revert use of labels instead of placeholders, since it breaks
mail notifications. #524
0.12.1 (2019-01-19)
-------------------
- Revert fix for duplicate slashes, as it prevents isso from
starting in some cases. #523
0.12.0 (2019-01-18)
-------------------
- Fix compatibility with new XML API.
- Don't enable admin interface with default password by default. #491
- Add support and documentation for "generic" imports.
- Remove potential duplicate slashes in URLs from
email links. #420
- Add data-isso-reply-notifications to attributes in configuration.
- Use default IP in imports if none is found. Fixes imports of some comments.
- embed: fix feed link creation on older browsers.
- Properly handle to field in mail notifications when using uWSGI spooler
- css: fix vertical alignment of notification checkbox
0.11.1 (2018-11-03)
-------------------
- Include pre-built minified JavaScript and CSS.
0.11.0 (2018-11-03)
-------------------
Bugs & features:
- Fix link in moderation mails if isso is setup on a sub-url (e.g. domain.tld/comments/)
- Add reply notifications
- Add admin interface
- Add links highlighting in comments
- Add apidoc
- Add rc.d script for FreeBSD
- Add the possibility to set CORS Origin through ISSO_CORS_ORIGIN environ variable
- Add preview button
- Add Atom feed at /feed?uri={thread-id}
- Add optionnal gravatar support
- Add nofollow noopener on links inside comments
- Add Dockerfile
- Upgraded to Misaka 2
- Some tests/travis/documentation improvements and fixes + pep8
Translations:
- Fix Chinese translation & typo in CJK
- Add Danish translation
- Add Hungarian translation
- Add Persian translation
- Improvement on german translation
0.10.6 (2016-09-22)
-------------------
- fix missing configuration field
0.10.5 (2016-09-20)
-------------------
- add support for different vote levels, #260
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg.
`"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given
one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg.
put a star on popular comments).
- add new post preview API endpoint, #254
- add an option for mandatory author, #257
- clients can now use `data-title` to get the HTML title for a new page, #252
- add finish translation and other minor bugfixes
0.10.4 (2016-04-12)
-------------------
- fix wrapper attribute when using data-isso-require-mail="true", #238
- fix reponse for OPTIONS response on Python 3, #242
0.10.3 (2016-02-24)
-------------------
- follow redirects, #193
0.10.2 (2016-02-21)
-------------------
- fix getAttribute return value
0.10.1 (2016-02-06)
-------------------
- fix empty author, email and website values when writing a comment
0.10 (2016-02-06)
-----------------
- add new configuration section for hash handling.
[hash]
salt = Eech7co8Ohloopo9Ol6baimi
algorithm = pbkdf2
You can customize the salt, choose different hash functions and tweak the
parameters for PBKDF2.
- Python 3.4+ validate TLS connections against the system's CA. Previously no
validation was in place, see PEP-446__ for details.
- add `fenced_code` and `no_intra_emphasis` to default configuration.
Fenced code allows to write code without indentation using `~~~` delimiters
(optionally with language identifier).
Intra emphasis would compile `foo_bar_baz` to foo<em>bar</em>baz. This
behavior is very confusing for users not knowing the Markdown spec in detail.
- new configuration to require an email when submitting comments, #199. Set
[guard]
require-email = true
and use `data-isso-require-email="true"` to enable this feature. Disabled by
default.
- new Bulgarian translation by sahwar, new Swedish translation by Gustav
Näslund – #143, new Vietnamese translation by Đinh Xuân Sâm, new Croatian
translation by streger, new Czech translation by Jan Chren
- fix SMTP setup without credentials, #174
- version pin Misaka to 1.x, html5lib to 0.9999999
.. __: https://www.python.org/dev/peps/pep-0466/
0.9.10 (2015-04-11)
-------------------
- fix regression in SMTP authentication, #174
0.9.9 (2015-03-04)
------------------
- several Python 3.x related bugfixes
- don't lose comment form if the server rejected the POST request, #144
- add localStorage fallback if QUOTA_EXCEEDED_ERR is thrown (e.g. Safari
private browsing)
- add '--empty-id' flag to Disqus import, because Disqus' export sucks
- (re)gain compatibility with Werkzeug 0.8 and really old html5lib versions
available in Debian Squeeze, #170 & #168
- add User-Agent when Isso requests the URL, an alternate way to #151 (add
'X-Isso' when requesting).
0.9.8 (2014-10-08)
------------------
- add compatibility with configparser==3.5.0b1, #128
0.9.7 (2014-09-25)
------------------
- fix SMTP authentication using CRAM-MD5 (incorrect usage of
`smtplib`), #126
0.9.6 (2014-08-18)
------------------
- remember name, email and website in localStorage, #119
- add option to hide voting feature, #115
data-isso-vote="true|false"
- remove email field from JSON responses
This is a quite serious issue. For the identicon, an expensive hash is used
to avoid the leakage of personal information like a real email address. A
`git blame` reveals, the email has been unintentionally exposed since the very
first release of Isso :-/
The testsuite now contains a dedicated test to prevent this error in the
future.
0.9.5 (2014-08-10)
------------------
- prevent no-break space ( ) insertion to enable manual line breaks using
two trailing spaces (as per Markdown convention), #112
- limit request size to 256 kb, #107
Previously unlimited or limited by proxy server). 256 kb is a rough
approximation of the next database schema with comments limited to 65535
characters and additional fields.
- add support for logging to file, #103
[general]
log-file =
- show timestamp when hovering <time>, #104
- fix a regression when editing comments with multiple paragraphs introduced
in 0.9.3 which would HTML escape manually inserted linebreaks.
0.9.4 (2014-07-09)
------------------
- fixed a regression when using Isso and Gevent
0.9.3 (2014-07-09)
------------------
- remove scrollIntoView while expanding further comments if a fragment is used
(e.g. #isso-thread brought you back to the top, unexpectedly)
- implement a custom Markdown renderer to support multi-line code listings. The
extension "fenced_code" is now enabled by default and generates HTML
compatible with Highlight.js__.
- escape HTML entities when editing a comment with raw HTML
- fix CSS for input
- remove isso.css from binary distribution to avoid confusion (it's still there
from the very first release, but modifications do not work)
.. __: http://highlightjs.org/
0.9 (2014-05-29)
----------------
- comment pagination by Srijan Choudhary, #15
Isso can now limit the amount of comments shown by default and add link to
show more. By default, all top-level comments are shown but only 5 nested
comments (per reply). You can override the settings:
isso-data-max-comments-top="N"
isso-data-max-comments-nested="N"
Where N is a number from 0 to infinity ("inf"). If you limit the amount of
shown top level comments, the overall comment count may be incorrect and a
known issue.
You can also configure the amount of comments shown per click (5 by default):
isso-data-reveal-on-click="N"
This feature also required a change in the comment structure. Previously, all
comments are stored tree-like but shown linearly. To ease the implementation
of pagination, the comment tree is now limited to a maximum depth of one.
Jeff Atwood explains, why `discussions are flat by design`__.
.. __: http://blog.codinghorror.com/web-discussions-flat-by-design/
When you upgrade, Isso will automatically normalize the tree and some
information gets lost. All new replies to a comment are now automatically a
direct child of the top-level comment.
- style improvements by William Dorffer, #39, #84 #90 and #91
Isso now longer uses a fat SCSS library, but plain CSS instead. The design is
now responsive and no longer sets global CSS rules.
- experimental WordPress import, #75
Isso should be able to import WXR 1.0-1.2 exports. The import code is based
on two WXR dumps I found (and created) and may not work for you. Please
report any failure.
- avatar changes, #49
You can now configure the client to not show avatars:
data-isso-avatar="false"
Also there is no longer an avatar shown next to the comment box. This is due
to the new CSS and removes two runtime dependencies.
- you may now set a full From header, #87
[smtp]
from = Foo Bar <spam@local>
- SMTP (all caps) is now recognized for notifications, #95
- Isso now ships a small demo site at /demo, #44
- a few bugfixes: Disqus import now anonymizes IP addresses, uWSGI spooling for
Python 3, HTTP-Referer fallback for HTTP-Origin
- remove Django's PBKDF2 implementation in favour of the PBKDF2 function
available in werkzeug 0.9 or higher. If you're still using werkzeug 0.8, Isso
imports passlib__ as fallback (if available).
This release also features a new templating engine Jade__ which replaces
Markup.js__. Jade can compile directly to JavaScript with a tiny runtime module
on the client. Along with the removal of sha1.js and pbkdf2.js and a few build
optimizations, the JS client now weighs only 40kb (12kb gzipped) – 52kb resp.
17kb before.
.. __: https://pypi.python.org/pypi/passlib
.. __: http://jade-lang.com/
.. __: https://github.com/adammark/Markup.js
0.8 (2014-03-28)
----------------
- replace ``<textarea>`` with ``<div contentedtiable="true">`` to remove the
sluggish auto-resize on input feature. If you use a custom CSS, replace
``textarea`` with ``.textarea`` and also set ``white-space: pre``.
- remove superscript extension from Markdown defaults as it may lead to
unexpected behavior for certain smileys such as "^^". To enable the extension,
add
[markup]
options = superscript
allowed-elements = sup
to your configuration.
- comment count requests are now bundled into a single POST request, but the old
API is still there (deprecated though).
- store *session-key* in database (once generated on database creation). That
means links to activate, edit or delete comments are now always valid even
when you restart Isso.
Currently statically set session keys in ``[general]`` are automatically
migrated into the database on startup and you will get a notice that you can
remove this option.
- fix undefined timestamp when client time differs for more than 1 second.
The human-readable "time ago" deltas have been refined to match `Moment.js`_
behavior.
- avatar colors and background can now be customized:
* ``data-isso-avatar-bg="#f0f0f0"`` sets the background color
* ``data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."`` sets possible
avatar colors (up to 8 colors are possible).
- new [markup] section to customize Misaka's Markdown generation (strikethrough,
superscript and autolink enabled by default). Furthermore, you can now allow
certain HTML elemenets and attributes in the generated output, e.g. to enable
images, set
[markup]
allowed-elements = img
allowed-attributes = src
Check docs/configuration/server.rst for more details.
- replace requirejs-domready with a (self-made) HTML5 idiom, #51
.. _Moment.js: http://momentjs.com/docs/#/displaying/fromnow/
0.7 (2014-01-29)
----------------
- fix malicious HTML injection (due to wrong API usage). All unknown/unsafe
HTML tags are now removed from the output (`html5lib` 0.99(9) or later) or
properly escaped (older `html5lib` versions).
See 36d702c and 3a1f92b for more details.
- remove kriskowal/q JS library (promises implementation) in favour of a
self-made 50 LoC implementation to ease packaging (for Debian), #51
- add documentation to display a comment counter, #56 and #57
- SMTP notifications now support STARTTLS and use this transport security
by default, #48 and #58. This also changes the configuration option from
`ssl = [yes|no]` to `security = [none|starttls|ssl]`.
- translation can now be made (and updated) with Transifex_. If you want to
take ownership for a language, contact me on IRC.
- fix french pluralform
- the (by default random) session-key is now shown on application startup
to make different keys per startup more visible
- use `threading.lock` by default for systems without semaphore support
.. _Transifex: https://www.transifex.com/projects/p/isso/
0.6 (2013-12-16)
----------------
Major improvements:
- override thread discovery with data-isso-id="...", #27
To use the same thread for different URLs, you can now add a custom
``data-isso-id="my-id"`` attribute which is used to identify and retrieve
comments (defaults to current URL aka `window.location.pathname`).
- `isso.dispatch` now dispatches multiple websites (= configurations) based on
URL prefixes
- fix a cross-site request forgery vulnerability for comment creation, voting,
editing and deletion, #40
- show modal dialog to confirm comment deletion and activation, #36
- new, comprehensive documentation based on reST + Sphinx:
http://posativ.org/docs (or docs/ in the repository). Also includes an
annotated `example.conf`, #43
- new italian and russian translations
Minor improvements:
- move `isso:application` to `isso.run:application` to avoid uneccessary
initialization in some cases (change module if you use uWSGI or Gunicorn)
- add Date header to email notifications, #42
- check for blank text in new comment, #41
- work around IE10's HTML5 abilities for custom data-attributes
- add support for Gunicorn (and other pre-forking WSGI servers)
0.5 (2013-11-17)
----------------
Major improvements:
- `listen` option replaces `host` and `port` to support UNIX domain sockets, #25
Instead of `host = localhost` and `port = 8080`, use
`listen = http://localhost:8080`. To listen on a UNIX domain socket, replace
`http://` with `unix://`, e.g. `unix:///tmp/isso.sock`.
- new option `notify` (in the general section) is used to choose (one or more)
notification backends (currently only SMTP is available, though). Isso will
no longer automatically use SMTP for notifications if the initial connection
succeeds.
- new options to control the client integration
* ``data-isso-css="false"`` prevents the client from appending the CSS to the
document. Enabled by default.
* ``data-isso-lang="de"`` overrides the useragent's preferred language (de, en
and fr are currently supported).
* ``data-isso-reply-to-self="true"`` should be set, when you allow reply to
own comments (see server configuration for details).
- add support for `gevent <http://www.gevent.org/>`_, a coroutine-based Python
networking library that uses greenlets (lightweight threads). Recommended
WSGI server when not running with uWSGI (unfortunately stable gevent is not
yet able to listen on a UNIX domain socket).
- fix a serious issue with the voters bloomfilter. During an Isso run, the
ip addresses from all commenters accumulated into the voters bloomfilter
for new comments. Thus, previous commenters could no longer vote other
comments. This fixes the rare occurences of #5.
In addition to this fix, the current voters bloomfilter will be re-initialized
if you are using Isso 0.4 or below (this is not necessary, but on the
other hand, the current bloomfilter for each comment is sort-of useless).
- french translation (thanks to @sploinga), #38
- support for multiple sites, part of #34
Minor improvements:
- `ipaddr` is now used as `ipaddress` fallback for Python 2.6 and 2.7, #32
- changed URL to activate and delete comments to `/id/<N:int>/activate` etc.
- import command uses `<link>` tag instead of `<id>` to extract the relative
URL path, #37
- import command now uses `isDeleted` to mark comments as deleted (and
eventually remove stale comments). This seems to affect only a few comments
from a previous WordPress import into Disqus.
- import command lists orphaned comments after import.
- import command now has a ``--dry-run`` option to do no actual operation on
the database.
0.4 (2013-11-05)
----------------
- Isso now handles cross-domain requests and cookies, fixes #24
- Isso for Python 2.x now supports werkzeug>=0.8
- limit email length to 254 to avoid Hash-DDoS
- override Isso API location with ``data-isso="..."`` in the script tag
- override HTML title parsing with a custom ``data-title="..."`` attribute
in ``<div id="isso-thread"></div>``
0.3 (2013-11-01)
----------------
- improve initial comment loading performance in the client
- cache slow REST requests, see #18
- add a SQLite trigger that detects and removes stale threads (= threads,
with all comments being removed) from the database when a comment is
removed.
- PyPi releases now include an uncompressed version of the JavaScript
files -- `embed.dev.js` and `count.dev.js` -- to track down errors.
- use uWSGI's internal locking instead of a self-made shared memory lock
0.2 (2013-10-29)
----------------
- initial PyPi release
| fliiiix | 8c306f45a24b6996d2fcc44d6564a552021ed03d | 79a774699cfb994b5098428bad154699e2d361cf | done | fliiiix | 61 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/tests/test_comments.py | # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testModerateComment(self):
id_ = 1
signed = self.app.sign(id_)
# Create new comment, should have mode=2 (pending moderation)
rv = self.client.post(
'/new?uri=/moderated', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 2)
self.assertEqual(self.app.db.comments.get(id_)["text"], "...")
# GET should return some html form
action = "activate"
rv_activate_get = self.client.get('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activate_get.status_code, 200)
self.assertIn(b"Activate: Are you sure?", rv_activate_get.data)
self.assertIn(b"http://invalid.local/moderated#isso-1", rv_activate_get.data)
# Activate comment
action = "activate"
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Comment has been activated")
# Activating should be idempotent
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Already activated")
# Comment should have mode=1 (activated)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 1)
# Edit comment
action = "edit"
rv_edit = self.client.post('/id/%d/%s/%s' % (id_, action, signed), data=json.dumps({"text": "new text"}))
self.assertEqual(rv_edit.status_code, 200)
self.assertEqual(json.loads(rv_edit.data)["id"], id_)
self.assertEqual(self.app.db.comments.get(id_)["text"], "new text")
# Wrong action on comment is handled by the routing
action = "foo"
rv_wrong_action = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_wrong_action.status_code, 404)
# Delete comment
action = "delete"
rv_deleted = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_deleted.status_code, 200)
self.assertEqual(rv_deleted.data, b"Comment has been deleted")
# Comment should no longer exist
self.assertEqual(self.app.db.comments.get(id_), None)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
# add default comment
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
def tearDown(self):
os.unlink(self.path)
def testUnsubscribe(self):
id_ = 1
email = "test@test.example"
key = self.app.sign(('unsubscribe', email))
# GET should return some html form
rv_unsubscribe_get = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_unsubscribe_get.status_code, 200)
self.assertIn(b"Successfully unsubscribed", rv_unsubscribe_get.data)
# Incomplete key should fail
key = self.app.sign(['unsubscribe'])
rv_incomplete_key = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_incomplete_key.status_code, 403)
# Wrong key type should fail
key = self.app.sign(1)
rv_wrong_key_type = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_wrong_key_type.status_code, 403)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | `rv_activate_get` | ix5 | 62 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/tests/test_comments.py | # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testModerateComment(self):
id_ = 1
signed = self.app.sign(id_)
# Create new comment, should have mode=2 (pending moderation)
rv = self.client.post(
'/new?uri=/moderated', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 2)
self.assertEqual(self.app.db.comments.get(id_)["text"], "...")
# GET should return some html form
action = "activate"
rv_activate_get = self.client.get('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activate_get.status_code, 200)
self.assertIn(b"Activate: Are you sure?", rv_activate_get.data)
self.assertIn(b"http://invalid.local/moderated#isso-1", rv_activate_get.data)
# Activate comment
action = "activate"
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Comment has been activated")
# Activating should be idempotent
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Already activated")
# Comment should have mode=1 (activated)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 1)
# Edit comment
action = "edit"
rv_edit = self.client.post('/id/%d/%s/%s' % (id_, action, signed), data=json.dumps({"text": "new text"}))
self.assertEqual(rv_edit.status_code, 200)
self.assertEqual(json.loads(rv_edit.data)["id"], id_)
self.assertEqual(self.app.db.comments.get(id_)["text"], "new text")
# Wrong action on comment is handled by the routing
action = "foo"
rv_wrong_action = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_wrong_action.status_code, 404)
# Delete comment
action = "delete"
rv_deleted = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_deleted.status_code, 200)
self.assertEqual(rv_deleted.data, b"Comment has been deleted")
# Comment should no longer exist
self.assertEqual(self.app.db.comments.get(id_), None)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
# add default comment
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
def tearDown(self):
os.unlink(self.path)
def testUnsubscribe(self):
id_ = 1
email = "test@test.example"
key = self.app.sign(('unsubscribe', email))
# GET should return some html form
rv_unsubscribe_get = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_unsubscribe_get.status_code, 200)
self.assertIn(b"Successfully unsubscribed", rv_unsubscribe_get.data)
# Incomplete key should fail
key = self.app.sign(['unsubscribe'])
rv_incomplete_key = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_incomplete_key.status_code, 403)
# Wrong key type should fail
key = self.app.sign(1)
rv_wrong_key_type = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_wrong_key_type.status_code, 403)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | Any reason for duplicating this test? | ix5 | 63 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/tests/test_comments.py | # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testModerateComment(self):
id_ = 1
signed = self.app.sign(id_)
# Create new comment, should have mode=2 (pending moderation)
rv = self.client.post(
'/new?uri=/moderated', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 2)
self.assertEqual(self.app.db.comments.get(id_)["text"], "...")
# GET should return some html form
action = "activate"
rv_activate_get = self.client.get('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activate_get.status_code, 200)
self.assertIn(b"Activate: Are you sure?", rv_activate_get.data)
self.assertIn(b"http://invalid.local/moderated#isso-1", rv_activate_get.data)
# Activate comment
action = "activate"
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Comment has been activated")
# Activating should be idempotent
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Already activated")
# Comment should have mode=1 (activated)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 1)
# Edit comment
action = "edit"
rv_edit = self.client.post('/id/%d/%s/%s' % (id_, action, signed), data=json.dumps({"text": "new text"}))
self.assertEqual(rv_edit.status_code, 200)
self.assertEqual(json.loads(rv_edit.data)["id"], id_)
self.assertEqual(self.app.db.comments.get(id_)["text"], "new text")
# Wrong action on comment is handled by the routing
action = "foo"
rv_wrong_action = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_wrong_action.status_code, 404)
# Delete comment
action = "delete"
rv_deleted = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_deleted.status_code, 200)
self.assertEqual(rv_deleted.data, b"Comment has been deleted")
# Comment should no longer exist
self.assertEqual(self.app.db.comments.get(id_), None)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
# add default comment
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
def tearDown(self):
os.unlink(self.path)
def testUnsubscribe(self):
id_ = 1
email = "test@test.example"
key = self.app.sign(('unsubscribe', email))
# GET should return some html form
rv_unsubscribe_get = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_unsubscribe_get.status_code, 200)
self.assertIn(b"Successfully unsubscribed", rv_unsubscribe_get.data)
# Incomplete key should fail
key = self.app.sign(['unsubscribe'])
rv_incomplete_key = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_incomplete_key.status_code, 403)
# Wrong key type should fail
key = self.app.sign(1)
rv_wrong_key_type = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_wrong_key_type.status_code, 403)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | Maybe use `uri=/moderated` (with slash) so that later on, the assert with `invalid.local/moderated` instead of `invalid.localmoderated` is not as confusing | ix5 | 64 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/tests/test_comments.py | # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testModerateComment(self):
id_ = 1
signed = self.app.sign(id_)
# Create new comment, should have mode=2 (pending moderation)
rv = self.client.post(
'/new?uri=/moderated', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 2)
self.assertEqual(self.app.db.comments.get(id_)["text"], "...")
# GET should return some html form
action = "activate"
rv_activate_get = self.client.get('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activate_get.status_code, 200)
self.assertIn(b"Activate: Are you sure?", rv_activate_get.data)
self.assertIn(b"http://invalid.local/moderated#isso-1", rv_activate_get.data)
# Activate comment
action = "activate"
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Comment has been activated")
# Activating should be idempotent
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Already activated")
# Comment should have mode=1 (activated)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 1)
# Edit comment
action = "edit"
rv_edit = self.client.post('/id/%d/%s/%s' % (id_, action, signed), data=json.dumps({"text": "new text"}))
self.assertEqual(rv_edit.status_code, 200)
self.assertEqual(json.loads(rv_edit.data)["id"], id_)
self.assertEqual(self.app.db.comments.get(id_)["text"], "new text")
# Wrong action on comment is handled by the routing
action = "foo"
rv_wrong_action = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_wrong_action.status_code, 404)
# Delete comment
action = "delete"
rv_deleted = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_deleted.status_code, 200)
self.assertEqual(rv_deleted.data, b"Comment has been deleted")
# Comment should no longer exist
self.assertEqual(self.app.db.comments.get(id_), None)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
# add default comment
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
def tearDown(self):
os.unlink(self.path)
def testUnsubscribe(self):
id_ = 1
email = "test@test.example"
key = self.app.sign(('unsubscribe', email))
# GET should return some html form
rv_unsubscribe_get = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_unsubscribe_get.status_code, 200)
self.assertIn(b"Successfully unsubscribed", rv_unsubscribe_get.data)
# Incomplete key should fail
key = self.app.sign(['unsubscribe'])
rv_incomplete_key = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_incomplete_key.status_code, 403)
# Wrong key type should fail
key = self.app.sign(1)
rv_wrong_key_type = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_wrong_key_type.status_code, 403)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | handled | ix5 | 65 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/tests/test_comments.py | # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testModerateComment(self):
id_ = 1
signed = self.app.sign(id_)
# Create new comment, should have mode=2 (pending moderation)
rv = self.client.post(
'/new?uri=/moderated', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 2)
self.assertEqual(self.app.db.comments.get(id_)["text"], "...")
# GET should return some html form
action = "activate"
rv_activate_get = self.client.get('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activate_get.status_code, 200)
self.assertIn(b"Activate: Are you sure?", rv_activate_get.data)
self.assertIn(b"http://invalid.local/moderated#isso-1", rv_activate_get.data)
# Activate comment
action = "activate"
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Comment has been activated")
# Activating should be idempotent
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Already activated")
# Comment should have mode=1 (activated)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 1)
# Edit comment
action = "edit"
rv_edit = self.client.post('/id/%d/%s/%s' % (id_, action, signed), data=json.dumps({"text": "new text"}))
self.assertEqual(rv_edit.status_code, 200)
self.assertEqual(json.loads(rv_edit.data)["id"], id_)
self.assertEqual(self.app.db.comments.get(id_)["text"], "new text")
# Wrong action on comment is handled by the routing
action = "foo"
rv_wrong_action = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_wrong_action.status_code, 404)
# Delete comment
action = "delete"
rv_deleted = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_deleted.status_code, 200)
self.assertEqual(rv_deleted.data, b"Comment has been deleted")
# Comment should no longer exist
self.assertEqual(self.app.db.comments.get(id_), None)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
# add default comment
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
def tearDown(self):
os.unlink(self.path)
def testUnsubscribe(self):
id_ = 1
email = "test@test.example"
key = self.app.sign(('unsubscribe', email))
# GET should return some html form
rv_unsubscribe_get = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_unsubscribe_get.status_code, 200)
self.assertIn(b"Successfully unsubscribed", rv_unsubscribe_get.data)
# Incomplete key should fail
key = self.app.sign(['unsubscribe'])
rv_incomplete_key = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_incomplete_key.status_code, 403)
# Wrong key type should fail
key = self.app.sign(1)
rv_wrong_key_type = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_wrong_key_type.status_code, 403)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | Using `id_` instead of my usage of private `_id` is much smarter, good catch! | ix5 | 66 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/tests/test_comments.py | # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testModerateComment(self):
id_ = 1
signed = self.app.sign(id_)
# Create new comment, should have mode=2 (pending moderation)
rv = self.client.post(
'/new?uri=/moderated', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 2)
self.assertEqual(self.app.db.comments.get(id_)["text"], "...")
# GET should return some html form
action = "activate"
rv_activate_get = self.client.get('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activate_get.status_code, 200)
self.assertIn(b"Activate: Are you sure?", rv_activate_get.data)
self.assertIn(b"http://invalid.local/moderated#isso-1", rv_activate_get.data)
# Activate comment
action = "activate"
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Comment has been activated")
# Activating should be idempotent
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Already activated")
# Comment should have mode=1 (activated)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 1)
# Edit comment
action = "edit"
rv_edit = self.client.post('/id/%d/%s/%s' % (id_, action, signed), data=json.dumps({"text": "new text"}))
self.assertEqual(rv_edit.status_code, 200)
self.assertEqual(json.loads(rv_edit.data)["id"], id_)
self.assertEqual(self.app.db.comments.get(id_)["text"], "new text")
# Wrong action on comment is handled by the routing
action = "foo"
rv_wrong_action = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_wrong_action.status_code, 404)
# Delete comment
action = "delete"
rv_deleted = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_deleted.status_code, 200)
self.assertEqual(rv_deleted.data, b"Comment has been deleted")
# Comment should no longer exist
self.assertEqual(self.app.db.comments.get(id_), None)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
# add default comment
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
def tearDown(self):
os.unlink(self.path)
def testUnsubscribe(self):
id_ = 1
email = "test@test.example"
key = self.app.sign(('unsubscribe', email))
# GET should return some html form
rv_unsubscribe_get = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_unsubscribe_get.status_code, 200)
self.assertIn(b"Successfully unsubscribed", rv_unsubscribe_get.data)
# Incomplete key should fail
key = self.app.sign(['unsubscribe'])
rv_incomplete_key = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_incomplete_key.status_code, 403)
# Wrong key type should fail
key = self.app.sign(1)
rv_wrong_key_type = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_wrong_key_type.status_code, 403)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | Incomplete, same for `rv_incomplete_key` | ix5 | 67 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/tests/test_comments.py | # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testModerateComment(self):
id_ = 1
signed = self.app.sign(id_)
# Create new comment, should have mode=2 (pending moderation)
rv = self.client.post(
'/new?uri=/moderated', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 2)
self.assertEqual(self.app.db.comments.get(id_)["text"], "...")
# GET should return some html form
action = "activate"
rv_activate_get = self.client.get('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activate_get.status_code, 200)
self.assertIn(b"Activate: Are you sure?", rv_activate_get.data)
self.assertIn(b"http://invalid.local/moderated#isso-1", rv_activate_get.data)
# Activate comment
action = "activate"
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Comment has been activated")
# Activating should be idempotent
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Already activated")
# Comment should have mode=1 (activated)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 1)
# Edit comment
action = "edit"
rv_edit = self.client.post('/id/%d/%s/%s' % (id_, action, signed), data=json.dumps({"text": "new text"}))
self.assertEqual(rv_edit.status_code, 200)
self.assertEqual(json.loads(rv_edit.data)["id"], id_)
self.assertEqual(self.app.db.comments.get(id_)["text"], "new text")
# Wrong action on comment is handled by the routing
action = "foo"
rv_wrong_action = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_wrong_action.status_code, 404)
# Delete comment
action = "delete"
rv_deleted = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_deleted.status_code, 200)
self.assertEqual(rv_deleted.data, b"Comment has been deleted")
# Comment should no longer exist
self.assertEqual(self.app.db.comments.get(id_), None)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
# add default comment
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
def tearDown(self):
os.unlink(self.path)
def testUnsubscribe(self):
id_ = 1
email = "test@test.example"
key = self.app.sign(('unsubscribe', email))
# GET should return some html form
rv_unsubscribe_get = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_unsubscribe_get.status_code, 200)
self.assertIn(b"Successfully unsubscribed", rv_unsubscribe_get.data)
# Incomplete key should fail
key = self.app.sign(['unsubscribe'])
rv_incomplete_key = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_incomplete_key.status_code, 403)
# Wrong key type should fail
key = self.app.sign(1)
rv_wrong_key_type = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_wrong_key_type.status_code, 403)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | its also what PEP8 tells you to do ;) | fliiiix | 68 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/tests/test_comments.py | # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| # -*- encoding: utf-8 -*-
import json
import os
import pkg_resources
import re
import tempfile
import unittest
from urllib.parse import urlencode
from werkzeug.wrappers import Response
from isso import Isso, core, config, dist
from isso.utils import http
from isso.views import comments
from fixtures import curl, loads, FakeIP, FakeHost, JSONClient
http.curl = curl
class TestComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
conf.set("general", "latest-enabled", "true")
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
self.get = self.client.get
self.put = self.client.put
self.post = self.client.post
self.delete = self.client.delete
def tearDown(self):
os.unlink(self.path)
def testGet(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['id'], 1)
self.assertEqual(rv['text'], '<p>Lorem ipsum ...</p>')
def testCreate(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertEqual(rv.status_code, 201)
self.assertIn("Set-Cookie", rv.headers)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Lorem ipsum ...</p>')
def textCreateWithNonAsciiText(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Здравствуй, мир!'}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
self.assertEqual(rv["mode"], 1)
self.assertEqual(rv["text"], '<p>Здравствуй, мир!</p>')
def testCreateMultiple(self):
a = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
b = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
c = self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.assertEqual(loads(a.data)["id"], 1)
self.assertEqual(loads(b.data)["id"], 2)
self.assertEqual(loads(c.data)["id"], 3)
def testCreateAndGetMultiple(self):
for i in range(20):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Spam'}))
r = self.get('/?uri=%2Fpath%2F')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 20)
def testCreateInvalidParent(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
invalid = self.post(
'/new?uri=test', data=json.dumps({'text': '...', 'parent': 2}))
self.assertEqual(loads(invalid.data)["parent"], 1)
def testVerifyFields(self):
def verify(comment):
return comments.API.verify(comment)[0]
# text is missing
self.assertFalse(verify({}))
# invalid types
self.assertFalse(verify({"text": "...", "parent": "xxx"}))
for key in ("author", "website", "email"):
self.assertFalse(verify({"text": True, key: 3.14}))
# text too short and/or blank
for text in ("", "\n\n\n"):
self.assertFalse(verify({"text": text}))
# email/website length
self.assertTrue(verify({"text": "...", "email": "*" * 254}))
self.assertTrue(
verify({"text": "...", "website": "google.de/" + "a" * 128}))
self.assertFalse(verify({"text": "...", "email": "*" * 1024}))
self.assertFalse(
verify({"text": "...", "website": "google.de/" + "*" * 1024}))
# valid website url
self.assertTrue(comments.isurl("example.tld"))
self.assertTrue(comments.isurl("http://example.tld"))
self.assertTrue(comments.isurl("https://example.tld"))
self.assertTrue(comments.isurl("https://example.tld:1337/"))
self.assertTrue(comments.isurl("https://example.tld:1337/foobar"))
self.assertTrue(comments.isurl(
"https://example.tld:1337/foobar?p=1#isso-thread"))
self.assertFalse(comments.isurl("ftp://example.tld/"))
self.assertFalse(comments.isurl("tel:+1234567890"))
self.assertFalse(comments.isurl("+1234567890"))
self.assertFalse(comments.isurl("spam"))
def testGetInvalid(self):
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(
self.get('/?uri=%2Fpath%2Fspam%2F&id=123').status_code, 200)
data = loads(self.get('/?uri=%2Fpath%2Fspam%2F&id=123').data)
self.assertEqual(len(data['replies']), 0)
self.assertEqual(self.get('/?uri=?uri=%foo%2F').status_code, 200)
data = loads(self.get('/?uri=?uri=%foo%2F').data)
self.assertEqual(len(data['replies']), 0)
def testGetLimited(self):
for i in range(20):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
r = self.get('/?uri=test&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testGetNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 1)
def testGetLimitedNested(self):
self.post('/new?uri=test', data=json.dumps({'text': '...'}))
for i in range(20):
self.post('/new?uri=test',
data=json.dumps({'text': '...', 'parent': 1}))
r = self.get('/?uri=test&parent=1&limit=10')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(len(rv['replies']), 10)
def testUpdate(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.put('/id/1', data=json.dumps({
'text': 'Hello World', 'author': 'me', 'website': 'http://example.com/'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
rv = loads(r.data)
self.assertEqual(rv['text'], 'Hello World')
self.assertEqual(rv['author'], 'me')
self.assertEqual(rv['website'], 'http://example.com/')
self.assertIn('modified', rv)
def testDelete(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data), None)
self.assertEqual(self.get('/id/1').status_code, 404)
def testFetchAuthorization(self):
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 200)
self.client.delete_cookie('localhost.local', '1')
r = self.get('/id/1?plain=1')
self.assertEqual(r.status_code, 403)
def testDeleteWithReference(self):
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'First', 'parent': 1}))
r = client.delete('/id/1')
self.assertEqual(r.status_code, 200)
self.assertEqual(loads(r.data)['mode'], 4)
self.assertIn('/path/', self.app.db.threads)
data = loads(client.get("/?uri=%2Fpath%2F").data)
self.assertEqual(data["total_replies"], 1)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=1').status_code, 200)
self.assertEqual(self.get('/?uri=%2Fpath%2F&id=2').status_code, 200)
r = client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
self.assertNotIn('/path/', self.app.db.threads)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testDeleteWithMultipleReferences(self):
"""
[ comment 1 ]
|
--- [ comment 2, ref 1 ]
|
--- [ comment 3, ref 1 ]
[ comment 4 ]
"""
client = JSONClient(self.app, Response)
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Second', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Third', 'parent': 1}))
client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Last'}))
client.delete('/id/1')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/2')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/3')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
client.delete('/id/4')
self.assertEqual(self.get('/?uri=%2Fpath%2F').status_code, 200)
data = loads(client.get('/?uri=%2Fpath%2F').data)
self.assertEqual(len(data['replies']), 0)
def testPathVariations(self):
paths = ['/sub/path/', '/path.html', '/sub/path.html', 'path', '/']
for path in paths:
self.assertEqual(self.post('/new?' + urlencode({'uri': path}),
data=json.dumps({'text': '...'})).status_code, 201)
for i, path in enumerate(paths):
self.assertEqual(
self.get('/?' + urlencode({'uri': path})).status_code, 200)
self.assertEqual(self.get('/id/%i' % (i + 1)).status_code, 200)
def testDeleteAndCreateByDifferentUsersButSamePostId(self):
mallory = JSONClient(self.app, Response)
mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'}))
mallory.delete('/id/1')
bob = JSONClient(self.app, Response)
bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'}))
self.assertEqual(mallory.delete('/id/1').status_code, 403)
self.assertEqual(bob.delete('/id/1').status_code, 200)
def testHash(self):
a = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Aaa"}))
b = self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "Bbb"}))
c = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "Ccc", "email": "..."}))
a = loads(a.data)
b = loads(b.data)
c = loads(c.data)
self.assertNotEqual(a['hash'], '192.168.1.1')
self.assertEqual(a['hash'], b['hash'])
self.assertNotEqual(a['hash'], c['hash'])
def testVisibleFields(self):
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({"text": "...", "invalid": "field"}))
self.assertEqual(rv.status_code, 201)
rv = loads(rv.data)
for key in comments.API.FIELDS:
if key in rv:
rv.pop(key)
self.assertListEqual(list(rv.keys()), [])
def testNoFeed(self):
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 404)
def testFeedEmpty(self):
self.conf.set("rss", "base", "https://example.org")
rv = self.get('/feed?uri=%2Fpath%2Fnothing')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"empty"')
data = rv.data.decode('utf-8')
self.assertEqual(data, """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>1970-01-01T01:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/nothing</id><title>Comments for example.org/path/nothing</title></feed>""")
def testFeed(self):
self.conf.set("rss", "base", "https://example.org")
self.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'}))
self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': '*Second*', 'parent': 1}))
rv = self.get('/feed?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(rv.headers['ETag'], '"1-2"')
data = rv.data.decode('utf-8')
data = re.sub('[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+Z',
'2018-04-01T10:00:00Z', data)
self.maxDiff = None
# Two accepted outputs, since different versions of Python sort attributes in different order.
self.assertIn(data, ["""<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to href="https://example.org/path/#isso-1" ref="tag:example.org,2018:/isso/1/1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>""", """<?xml version=\'1.0\' encoding=\'utf-8\'?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0"><updated>2018-04-01T10:00:00Z</updated><id>tag:example.org,2018:/isso/thread/path/</id><title>Comments for example.org/path/</title><entry><id>tag:example.org,2018:/isso/1/2</id><title>Comment #2</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-2" /><content type="html"><p><em>Second</em></p></content><thr:in-reply-to ref="tag:example.org,2018:/isso/1/1" href="https://example.org/path/#isso-1" /></entry><entry><id>tag:example.org,2018:/isso/1/1</id><title>Comment #1</title><updated>2018-04-01T10:00:00Z</updated><author><name /></author><link href="https://example.org/path/#isso-1" /><content type="html"><p>First</p></content></entry></feed>"""])
def testCounts(self):
self.assertEqual(self.get('/count?uri=%2Fpath%2F').status_code, 404)
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 1)
for x in range(3):
self.post('/new?uri=%2Fpath%2F', data=json.dumps({"text": "..."}))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 200)
self.assertEqual(loads(rv.data), 4)
for x in range(4):
self.delete('/id/%i' % (x + 1))
rv = self.get('/count?uri=%2Fpath%2F')
self.assertEqual(rv.status_code, 404)
def testMultipleCounts(self):
expected = {'a': 1, 'b': 2, 'c': 0}
for uri, count in expected.items():
for _ in range(count):
self.post('/new?uri=%s' %
uri, data=json.dumps({"text": "..."}))
rv = self.post('/count', data=json.dumps(list(expected.keys())))
self.assertEqual(loads(rv.data), list(expected.values()))
def testModify(self):
self.post('/new?uri=test', data=json.dumps({"text": "Tpyo"}))
self.put('/id/1', data=json.dumps({"text": "Tyop"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Tyop</p>")
self.put('/id/1', data=json.dumps({"text": "Typo"}))
self.assertEqual(loads(self.get('/id/1').data)["text"], "<p>Typo</p>")
def testDeleteCommentRemovesThread(self):
self.client.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
self.assertIn('/', self.app.db.threads)
self.client.delete('/id/1')
self.assertNotIn('/', self.app.db.threads)
def testCSRF(self):
js = "application/json"
form = "application/x-www-form-urlencoded"
self.post('/new?uri=%2F', data=json.dumps({"text": "..."}))
# no header is fine (default for XHR)
self.assertEqual(
self.post('/id/1/dislike', content_type="").status_code, 200)
# x-www-form-urlencoded is definitely not RESTful
self.assertEqual(
self.post('/id/1/dislike', content_type=form).status_code, 403)
self.assertEqual(self.post('/new?uri=%2F', data=json.dumps({"text": "..."}),
content_type=form).status_code, 403)
# just for the record
self.assertEqual(
self.post('/id/1/dislike', content_type=js).status_code, 200)
def testPreview(self):
response = self.post(
'/preview', data=json.dumps({'text': 'This is **mark***down*'}))
self.assertEqual(response.status_code, 200)
rv = loads(response.data)
self.assertEqual(
rv["text"], '<p>This is <strong>mark</strong><em>down</em></p>')
def testLatestOk(self):
# load some comments in a mix of posts
saved = []
for idx, post_id in enumerate([1, 2, 2, 1, 2, 1, 3, 1, 4, 2, 3, 4, 1, 2]):
text = 'text-{}'.format(idx)
post_uri = 'test-{}'.format(post_id)
self.post('/new?uri=' + post_uri, data=json.dumps({'text': text}))
saved.append((post_uri, text))
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 200)
body = loads(response.data)
expected_items = saved[-5:] # latest 5
for reply, expected in zip(body, expected_items):
expected_uri, expected_text = expected
self.assertIn(expected_text, reply['text'])
self.assertEqual(expected_uri, reply['uri'])
def testLatestWithoutLimit(self):
response = self.get('/latest')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNaN(self):
response = self.get('/latest?limit=WAT')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitNegative(self):
response = self.get('/latest?limit=-12')
self.assertEqual(response.status_code, 400)
def testLatestBadLimitZero(self):
response = self.get('/latest?limit=0')
self.assertEqual(response.status_code, 400)
def testLatestNotEnabled(self):
# disable the endpoint
self.conf.set("general", "latest-enabled", "false")
response = self.get('/latest?limit=5')
self.assertEqual(response.status_code, 404)
class TestHostDependent(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(os.path.join(dist.location, dist.project_name, "defaults.ini"))
conf.set("general", "dbpath", self.path)
self.conf = conf
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.client = JSONClient(self.app, Response)
self.post = self.client.post
def tearDown(self):
os.unlink(self.path)
def testSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testInSecureCookieNoConf(self):
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
def testSameSiteConfNone(self):
# By default, isso should set SameSite=Lax when served over http
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "http")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "None")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertNotIn("Secure", rv.headers["Set-Cookie"])
self.assertNotIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=None", rv.headers["Set-Cookie"])
def testSameSiteConfLax(self):
# By default, isso should set SameSite=None when served over https
self.app.wsgi_app = FakeHost(self.app.wsgi_app, "isso-dev.local", "https")
# Conf overrides SameSite setting
self.conf.set("server", "samesite", "Lax")
rv = self.post('/new?uri=%2Fpath%2F',
data=json.dumps({'text': 'Lorem ipsum ...'}))
self.assertIn("Secure", rv.headers["Set-Cookie"])
self.assertIn("Secure", rv.headers["X-Set-Cookie"])
self.assertIn("SameSite=Lax", rv.headers["Set-Cookie"])
class TestModeratedComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def tearDown(self):
os.unlink(self.path)
def testAddComment(self):
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
data = loads(self.client.get('/?uri=test').data)
self.assertEqual(len(data['replies']), 0)
self.app.db.comments.activate(1)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testModerateComment(self):
id_ = 1
signed = self.app.sign(id_)
# Create new comment, should have mode=2 (pending moderation)
rv = self.client.post(
'/new?uri=/moderated', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
self.assertEqual(self.client.get('/id/1').status_code, 200)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 2)
self.assertEqual(self.app.db.comments.get(id_)["text"], "...")
# GET should return some html form
action = "activate"
rv_activate_get = self.client.get('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activate_get.status_code, 200)
self.assertIn(b"Activate: Are you sure?", rv_activate_get.data)
self.assertIn(b"http://invalid.local/moderated#isso-1", rv_activate_get.data)
# Activate comment
action = "activate"
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Comment has been activated")
# Activating should be idempotent
rv_activated = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_activated.status_code, 200)
self.assertEqual(rv_activated.data, b"Already activated")
# Comment should have mode=1 (activated)
self.assertEqual(self.app.db.comments.get(id_)["mode"], 1)
# Edit comment
action = "edit"
rv_edit = self.client.post('/id/%d/%s/%s' % (id_, action, signed), data=json.dumps({"text": "new text"}))
self.assertEqual(rv_edit.status_code, 200)
self.assertEqual(json.loads(rv_edit.data)["id"], id_)
self.assertEqual(self.app.db.comments.get(id_)["text"], "new text")
# Wrong action on comment is handled by the routing
action = "foo"
rv_wrong_action = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_wrong_action.status_code, 404)
# Delete comment
action = "delete"
rv_deleted = self.client.post('/id/%d/%s/%s' % (id_, action, signed))
self.assertEqual(rv_deleted.status_code, 200)
self.assertEqual(rv_deleted.data, b"Comment has been deleted")
# Comment should no longer exist
self.assertEqual(self.app.db.comments.get(id_), None)
class TestUnsubscribe(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
# add default comment
rv = self.client.post(
'/new?uri=test', data=json.dumps({"text": "..."}))
self.assertEqual(rv.status_code, 202)
def tearDown(self):
os.unlink(self.path)
def testUnsubscribe(self):
id_ = 1
email = "test@test.example"
key = self.app.sign(('unsubscribe', email))
# GET should return some html form
rv_unsubscribe_get = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_unsubscribe_get.status_code, 200)
self.assertIn(b"Successfully unsubscribed", rv_unsubscribe_get.data)
# Incomplete key should fail
key = self.app.sign(['unsubscribe'])
rv_incomplete_key = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_incomplete_key.status_code, 403)
# Wrong key type should fail
key = self.app.sign(1)
rv_wrong_key_type = self.client.get('/id/%d/unsubscribe/%s/%s' % (id_, email, key))
self.assertEqual(rv_wrong_key_type.status_code, 403)
class TestPurgeComments(unittest.TestCase):
def setUp(self):
fd, self.path = tempfile.mkstemp()
conf = config.load(
pkg_resources.resource_filename('isso', 'defaults.ini'))
conf.set("general", "dbpath", self.path)
conf.set("moderation", "enabled", "true")
conf.set("guard", "enabled", "off")
conf.set("hash", "algorithm", "none")
class App(Isso, core.Mixin):
pass
self.app = App(conf)
self.app.wsgi_app = FakeIP(self.app.wsgi_app, "192.168.1.1")
self.client = JSONClient(self.app, Response)
def testPurgeDoesNoHarm(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.activate(1)
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/?uri=test').status_code, 200)
def testPurgeWorks(self):
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(0)
self.assertEqual(self.client.get('/id/1').status_code, 404)
self.client.post('/new?uri=test', data=json.dumps({"text": "..."}))
self.app.db.comments.purge(3600)
self.assertEqual(self.client.get('/id/1').status_code, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | nope this is a rebase mistake i overlooked | fliiiix | 69 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/unsubscribe/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>Successfully unsubscribed</head>
<body>
<p>You have been unsubscribed from replies in the given conversation.</p>
</body>
</html>
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if not isinstance(rv, list) or len(rv) != 2:
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,edit,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Comment has been deleted
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Comment has been activated", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Comment has been deleted", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | "Comment deleted" / "Comment has been deleted" ? | ix5 | 70 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/unsubscribe/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>Successfully unsubscribed</head>
<body>
<p>You have been unsubscribed from replies in the given conversation.</p>
</body>
</html>
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if not isinstance(rv, list) or len(rv) != 2:
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,edit,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Comment has been deleted
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Comment has been activated", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Comment has been deleted", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | "Comment activated" / "Comment has been activated" ? | ix5 | 71 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/unsubscribe/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>Successfully unsubscribed</head>
<body>
<p>You have been unsubscribed from replies in the given conversation.</p>
</body>
</html>
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if not isinstance(rv, list) or len(rv) != 2:
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,edit,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Comment has been deleted
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Comment has been activated", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Comment has been deleted", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | dito | ix5 | 72 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/unsubscribe/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>Successfully unsubscribed</head>
<body>
<p>You have been unsubscribed from replies in the given conversation.</p>
</body>
</html>
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if not isinstance(rv, list) or len(rv) != 2:
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,edit,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Comment has been deleted
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Comment has been activated", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Comment has been deleted", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | Maybe mention here that the key is also base64-encoded.
The stray `['unsubscribe', email]` here is also a bit confusing.
Maybe put it on a new line with "Expected syntax" or something. | ix5 | 73 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/unsubscribe/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>Successfully unsubscribed</head>
<body>
<p>You have been unsubscribed from replies in the given conversation.</p>
</body>
</html>
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if not isinstance(rv, list) or len(rv) != 2:
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,edit,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Comment has been deleted
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Comment has been activated", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Comment has been deleted", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | Pushed to your branch with my suggested change. I've left the base64 encoding part out because there's also a signature attached, which would just be confusing. | ix5 | 74 |
posativ/isso | 805 | views: moderation: Add unit tests, proper response instead of "Yo", apiDoc clarifications | Things this PR addresses:
* Replace Yo response from moderation with a more appropriate response
* Add tests for moderation
* Add tests for unsubscribe and fix doc string
Contributes to #755 | null | 2022-02-26 15:47:59+00:00 | 2022-03-05 18:11:46+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from configparser import NoOptionError
from datetime import datetime, timedelta
from html import escape
from io import BytesIO as StringIO
from urllib.parse import unquote, urlparse
from xml.etree import ElementTree as ET
from itsdangerous import SignatureExpired, BadSignature
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from werkzeug.http import dump_cookie
from werkzeug.routing import Rule
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from werkzeug.wsgi import get_current_url
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.utils.hash import md5, sha1
from isso.views import requires
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
# These configuration records can be read out by client
self.public_conf = {}
self.public_conf["reply-to-self"] = isso.conf.getboolean("guard", "reply-to-self")
self.public_conf["require-email"] = isso.conf.getboolean("guard", "require-email")
self.public_conf["require-author"] = isso.conf.getboolean("guard", "require-author")
self.public_conf["reply-notifications"] = isso.conf.getboolean("general", "reply-notifications")
self.public_conf["gravatar"] = isso.conf.getboolean("general", "gravatar")
if self.public_conf["gravatar"]:
self.public_conf["avatar"] = False
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/unsubscribe/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>Successfully unsubscribed</head>
<body>
<p>You have been unsubscribed from replies in the given conversation.</p>
</body>
</html>
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if not isinstance(rv, list) or len(rv) != 2:
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,edit,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Comment has been deleted
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Comment has been activated", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Comment has been deleted", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain),
'config': self.public_conf
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fliiiix | ae6dc847d9bc460fa6edc97159db8adc57590eea | 8bf84595492002acad3622cb8ed8c161430cb605 | thanks :+1: | fliiiix | 75 |
posativ/isso | 802 | setup.py, README: Generate proper Project Description for PyPi | ### setup.py: Include README in pypi upload
This allows for more information by embedding the README at https://pypi.org/project/isso/ as a "Project Description".
### README: ~~Point LICENSE to current GH master,~~ shuffle sections a bit
~~Reasoning: Use absolute link to allow embedding the rendered README on pypi (where the relative-path LICENSE is not available).~~ | null | 2022-02-23 21:38:43+00:00 | 2022-02-26 21:08:05+00:00 | README.md | # Isso – a commenting server similar to Disqus
Isso – *Ich schrei sonst* – is a lightweight commenting server written in
Python and JavaScript. It aims to be a drop-in replacement for
[Disqus](http://disqus.com).
![Isso in Action](http://posativ.org/~tmp/isso-sample.png)
See [posativ.org/isso](http://posativ.org/isso/) for more details.
## License
MIT, see [LICENSE](LICENSE).
## Development
Refer to the docs for
[Installing from Source](https://posativ.org/isso/docs/install/#install-from-source).
| # Isso – a commenting server similar to Disqus
Isso – *Ich schrei sonst* – is a lightweight commenting server written in
Python and JavaScript. It aims to be a drop-in replacement for
[Disqus](http://disqus.com).
See **[posativ.org/isso](http://posativ.org/isso/)** for more details and
documentation.
![Isso in Action](http://posativ.org/~tmp/isso-sample.png)
## License
MIT, see [LICENSE](LICENSE).
## Development
Refer to the docs for
[Installing from Source](https://posativ.org/isso/docs/install/#install-from-source).
| ix5 | 74326fbe6ab6ea4d91ab9d9d6aa47de119883d25 | ae6dc847d9bc460fa6edc97159db8adc57590eea | This breaks things for forks, can we just refer to the local file? | jelmer | 76 |
posativ/isso | 802 | setup.py, README: Generate proper Project Description for PyPi | ### setup.py: Include README in pypi upload
This allows for more information by embedding the README at https://pypi.org/project/isso/ as a "Project Description".
### README: ~~Point LICENSE to current GH master,~~ shuffle sections a bit
~~Reasoning: Use absolute link to allow embedding the rendered README on pypi (where the relative-path LICENSE is not available).~~ | null | 2022-02-23 21:38:43+00:00 | 2022-02-26 21:08:05+00:00 | README.md | # Isso – a commenting server similar to Disqus
Isso – *Ich schrei sonst* – is a lightweight commenting server written in
Python and JavaScript. It aims to be a drop-in replacement for
[Disqus](http://disqus.com).
![Isso in Action](http://posativ.org/~tmp/isso-sample.png)
See [posativ.org/isso](http://posativ.org/isso/) for more details.
## License
MIT, see [LICENSE](LICENSE).
## Development
Refer to the docs for
[Installing from Source](https://posativ.org/isso/docs/install/#install-from-source).
| # Isso – a commenting server similar to Disqus
Isso – *Ich schrei sonst* – is a lightweight commenting server written in
Python and JavaScript. It aims to be a drop-in replacement for
[Disqus](http://disqus.com).
See **[posativ.org/isso](http://posativ.org/isso/)** for more details and
documentation.
![Isso in Action](http://posativ.org/~tmp/isso-sample.png)
## License
MIT, see [LICENSE](LICENSE).
## Development
Refer to the docs for
[Installing from Source](https://posativ.org/isso/docs/install/#install-from-source).
| ix5 | 74326fbe6ab6ea4d91ab9d9d6aa47de119883d25 | ae6dc847d9bc460fa6edc97159db8adc57590eea | You cannot link to package resources inside PyPi, even if you include them in `MANIFEST.in`.
(I tested via https://test.pypi.org/project/isso-testpypi/ and the link goes to a 404, as you'd expect: https://test.pypi.org/project/isso-testpypi/LICENSE ) | ix5 | 77 |
posativ/isso | 801 | js: Add Jest testing | As discussed in https://github.com/posativ/isso/issues/754, add some basic Jest testing config and examples to facilitate finally writing some frontend code tests.
---
**Note:** End-to-end tests using `puppeteer` were split off and moved into https://github.com/posativ/isso/pull/807
---
### Terminology
- **[Jest](https://jestjs.io/)** is a Javascript testing framework. It is mainly used here for unit tests.
### Running
Install the needed packages:
```sh
npm install
```
Then run:
- `npm run test-unit` for Jest unit tests
---
Highly **WIP** at the moment, but could be useful to someone else working on the same issues. Please communicate and collaborate!
Depends on https://github.com/posativ/isso/pull/800. ~~I have temporarily changed the base to that branch to make it easier to review this change.~~ | null | 2022-02-19 16:54:25+00:00 | 2022-03-21 20:42:10+00:00 | package.json | {
"name": "isso",
"author": "Martin Zimmermann",
"description": "lightweight Disquis alternative",
"license": "MIT",
"repository": "github:posativ/isso",
"dependencies": {},
"scripts": {
"build-dev": "webpack --config isso/js/webpack.config.js --config-name dev",
"watch-dev": "webpack --config isso/js/webpack.config.js --config-name dev --watch",
"build-prod": "webpack --config isso/js/webpack.config.js --merge --config-name dev --config-name prod"
},
"devDependencies": {
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2"
}
}
| {
"name": "isso",
"author": "Martin Zimmermann",
"description": "lightweight Disquis alternative",
"license": "MIT",
"repository": "github:posativ/isso",
"dependencies": {},
"scripts": {
"test": "jest --config isso/js/jest.config.js isso/js/tests/" ,
"test-unit": "jest --config isso/js/jest.config.js isso/js/tests/unit/",
"build-dev": "webpack --config isso/js/webpack.config.js --config-name dev",
"watch-dev": "webpack --config isso/js/webpack.config.js --config-name dev --watch",
"build-prod": "webpack --config isso/js/webpack.config.js --merge --config-name dev --config-name prod"
},
"devDependencies": {
"jest": "^27.5.0",
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2"
}
}
| ix5 | 3c7ac68a4e0d320832fab068dfb7c1812363b182 | 7a1ae20cb0e94164df49ac19388c6b4163dea054 | "jest-puppeteer" is missing ;) | Lucas-C | 78 |
posativ/isso | 801 | js: Add Jest testing | As discussed in https://github.com/posativ/isso/issues/754, add some basic Jest testing config and examples to facilitate finally writing some frontend code tests.
---
**Note:** End-to-end tests using `puppeteer` were split off and moved into https://github.com/posativ/isso/pull/807
---
### Terminology
- **[Jest](https://jestjs.io/)** is a Javascript testing framework. It is mainly used here for unit tests.
### Running
Install the needed packages:
```sh
npm install
```
Then run:
- `npm run test-unit` for Jest unit tests
---
Highly **WIP** at the moment, but could be useful to someone else working on the same issues. Please communicate and collaborate!
Depends on https://github.com/posativ/isso/pull/800. ~~I have temporarily changed the base to that branch to make it easier to review this change.~~ | null | 2022-02-19 16:54:25+00:00 | 2022-03-21 20:42:10+00:00 | package.json | {
"name": "isso",
"author": "Martin Zimmermann",
"description": "lightweight Disquis alternative",
"license": "MIT",
"repository": "github:posativ/isso",
"dependencies": {},
"scripts": {
"build-dev": "webpack --config isso/js/webpack.config.js --config-name dev",
"watch-dev": "webpack --config isso/js/webpack.config.js --config-name dev --watch",
"build-prod": "webpack --config isso/js/webpack.config.js --merge --config-name dev --config-name prod"
},
"devDependencies": {
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2"
}
}
| {
"name": "isso",
"author": "Martin Zimmermann",
"description": "lightweight Disquis alternative",
"license": "MIT",
"repository": "github:posativ/isso",
"dependencies": {},
"scripts": {
"test": "jest --config isso/js/jest.config.js isso/js/tests/" ,
"test-unit": "jest --config isso/js/jest.config.js isso/js/tests/unit/",
"build-dev": "webpack --config isso/js/webpack.config.js --config-name dev",
"watch-dev": "webpack --config isso/js/webpack.config.js --config-name dev --watch",
"build-prod": "webpack --config isso/js/webpack.config.js --merge --config-name dev --config-name prod"
},
"devDependencies": {
"jest": "^27.5.0",
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2"
}
}
| ix5 | 3c7ac68a4e0d320832fab068dfb7c1812363b182 | 7a1ae20cb0e94164df49ac19388c6b4163dea054 | Adding `jest-puppeteer` to `devDependencies` will automatically pull in a 400Mb+ download of headless chrome, as explained earlier. That's why I'm a bit hesitant to add it here.
Imo it should be up to the user whether they need to run the end-to-end tests.
Maybe there's an option to configure the package _before_ installing to not pull in the chrome download automatically? | ix5 | 79 |
posativ/isso | 800 | [MAJOR] js: Move to webpack, pug from r.js, jade | # Introduction
As already discussed in https://github.com/posativ/isso/issues/754, try to make Isso more maintainable by facilitating modern testing practices.
This PR is a bit massive, but trying to make `pug` or other updated deps play nice with RequireJs just for the sake of a clean history is not something I'm prepared to do.
So, here goes:
---
### js: Move to webpack, pug from r.js, jade
In the interest of maintainability and integration with other testing tools, get rid of `RequireJS` (sometimes also called `r.js` or `requirejs`)
This necessitates the following changes:
- Removing the `almond` (`AMD`) module loader (superseded by webpack internals)
- Removing `requirejs-text` for loading static resources (superseded by webpack `asset/source` loader)
- Removing `jade` templating engine (superseded by `pug`, which represents the original `jade` project that had to be renamed due to trademark issues)
`pug` v2+ no longer accepts `'mystr-{#foo.bar}'`-style variables inside attributes, so `*.pug` templates need to be changed accordingly (`mystr' + foo.bar`)
Note: templates have been moved to `templates/` directory and renamed from `.jade` to `.pug`.
- `jade-runtime` and accompanying shims (superseded by simply `pug-runtime`)
- Move `.svg` files inside own dir, simplify loading via `webpack`'s `asset/source`
- Add `webpack` config
- Add build scripts to `package.json`
- Adjust `Makefile` to use `webpack` via `npm run`
- Emit JS source map files from `webpack` (eases debugging)
- `.gitignore` JS source map files
While RequireJS utilized the following syntax:
```
define(["app/foo"], function(foo) {
var bar = doSomeStuff...
return bar;
})
```
Jest and other testing libraries need the NodeJS standard `CommonJS` style:
```
const foo = require("app/foo");
var bar = doSomeStuff...
module.exports = { bar };
```
Note: ES6/ECMAScript2015-style `import` has not been used since it would need transpilation via e.g. `babel` to be understood by Jest.
The RequireJS-style wrapping of all code inside `define({...})` caused everything to be indented by at least one level.
To keep the changes in this commit manageable, indentation will be removed in a later commit.
### isso: js: treewide: De-indent one level
Since switching from RequireJS to CommonJS syntax, the `define()` wrapper is no longer needed and as such, the the code formerly inside parentheses can be de-indented by one level.
### isso: js: i18: RequireJS to module.exports
(Just an extension of previous commit, to avoid touching too many files at once)
### demo: Use dev version of embed.js
This makes it easier to debug when testing. The demo shouldn't be user-facing, but either way, the performance penalty should be outweighed by debugging benefits.
### isso: js: Reduce deps for app/lib/
(Just a minor commit to make the following unit tests easier)
---
# Verifying
You can verify this commit by checking out this PR:
```sh
git clone https://github.com/posativ/isso isso
cd isso/
git fetch origin pull/800/head:pull-800
git checkout pull-800
```
And then installing everything as documented in [docs: Install from Source](https://posativ.org/isso/docs/install/#install-from-source).
Then, either embed Isso into your site or use the demo at [localhost:8080/demo](http://localhost:8080/demo)
---
A note for people from the future: You can use `git blame --ignore-rev=<sha>` to "ignore" the de-indent commits. See [A better git blame](https://www.michaelheap.com/git-ignore-rev/).
Note to myself: We can probably ditch the templates altogether and simply use plain html with javascript string interpolation. That way, we lose `pug`, `pug-loader` and `pug-runtime`, which would make the bundle significantly smaller. | null | 2022-02-19 16:30:50+00:00 | 2022-03-20 20:12:35+00:00 | isso/js/app/lib/identicons.js | /*
Copyright (C) 2013 Gregory Schier <gschier1990@gmail.com>
Copyright (C) 2013 Martin Zimmermann <info@posativ.org>
Inspired by http://codepen.io/gschier/pen/GLvAy
*/
define(["app/lib/promise", "app/config"], function(Q, config) {
"use strict";
// Number of squares width and height
var GRID = 5;
var pad = function(n, width) {
return n.length >= width ? n : new Array(width - n.length + 1).join("0") + n;
};
/**
* Fill in a square on the canvas.
*/
var fill = function(svg, x, y, padding, size, color) {
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", padding + x * size);
rect.setAttribute("y", padding + y * size);
rect.setAttribute("width", size);
rect.setAttribute("height", size);
rect.setAttribute("style", "fill: " + color);
svg.appendChild(rect);
};
/**
* Pick random squares to fill in.
*/
var generateIdenticon = function(key, padding, size) {
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("version", "1.1");
svg.setAttribute("viewBox", "0 0 " + size + " " + size);
svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
svg.setAttribute("shape-rendering", "crispEdges");
fill(svg, 0, 0, 0, size + 2*padding, config["avatar-bg"]);
if (typeof key === null) {
return svg;
}
Q.when(key, function(key) {
var hash = pad((parseInt(key.substr(-16), 16) % Math.pow(2, 18)).toString(2), 18),
index = 0;
svg.setAttribute("data-hash", key);
var i = parseInt(hash.substring(hash.length - 3, hash.length), 2),
color = config["avatar-fg"][i % config["avatar-fg"].length];
for (var x=0; x<Math.ceil(GRID/2); x++) {
for (var y=0; y<GRID; y++) {
if (hash.charAt(index) === "1") {
fill(svg, x, y, padding, 8, color);
// fill right sight symmetrically
if (x < Math.floor(GRID/2)) {
fill(svg, (GRID-1) - x, y, padding, 8, color);
}
}
index++;
}
}
});
return svg;
};
var generateBlank = function(height, width) {
var blank = parseInt([
0, 1, 1, 1, 1,
1, 0, 1, 1, 0,
1, 1, 1, 1, 1, /* purple: */ 0, 1, 0
].join(""), 2).toString(16);
var el = generateIdenticon(blank, height, width);
el.setAttribute("className", "blank"); // IE10 does not support classList on SVG elements, duh.
return el;
};
return {
generate: generateIdenticon,
blank: generateBlank
};
});
| /*
Copyright (C) 2013 Gregory Schier <gschier1990@gmail.com>
Copyright (C) 2013 Martin Zimmermann <info@posativ.org>
Inspired by http://codepen.io/gschier/pen/GLvAy
*/
const Q = require("app/lib/promise");
"use strict";
// Number of squares width and height
var GRID = 5;
var pad = function(n, width) {
return n.length >= width ? n : new Array(width - n.length + 1).join("0") + n;
};
/**
* Fill in a square on the canvas.
*/
var fill = function(svg, x, y, padding, size, color) {
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", padding + x * size);
rect.setAttribute("y", padding + y * size);
rect.setAttribute("width", size);
rect.setAttribute("height", size);
rect.setAttribute("style", "fill: " + color);
svg.appendChild(rect);
};
/**
* Pick random squares to fill in.
*/
var generateIdenticon = function(key, padding, size, config) {
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("version", "1.1");
svg.setAttribute("viewBox", "0 0 " + size + " " + size);
svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
svg.setAttribute("shape-rendering", "crispEdges");
fill(svg, 0, 0, 0, size + 2*padding, config["avatar-bg"]);
if (typeof key === null) {
return svg;
}
Q.when(key, function(key) {
var hash = pad((parseInt(key.substr(-16), 16) % Math.pow(2, 18)).toString(2), 18),
index = 0;
svg.setAttribute("data-hash", key);
var i = parseInt(hash.substring(hash.length - 3, hash.length), 2),
color = config["avatar-fg"][i % config["avatar-fg"].length];
for (var x=0; x<Math.ceil(GRID/2); x++) {
for (var y=0; y<GRID; y++) {
if (hash.charAt(index) === "1") {
fill(svg, x, y, padding, 8, color);
// fill right sight symmetrically
if (x < Math.floor(GRID/2)) {
fill(svg, (GRID-1) - x, y, padding, 8, color);
}
}
index++;
}
}
});
return svg;
};
/* TODO: This function is currently unused and should be removed */
var generateBlank = function(height, width, config) {
var blank = parseInt([
0, 1, 1, 1, 1,
1, 0, 1, 1, 0,
1, 1, 1, 1, 1, /* purple: */ 0, 1, 0
].join(""), 2).toString(16);
var el = generateIdenticon(blank, height, width, config);
el.setAttribute("className", "blank"); // IE10 does not support classList on SVG elements, duh.
return el;
};
module.exports = {
generate: generateIdenticon,
blank: generateBlank,
};
| ix5 | 4d7a05f22b4dd3fb870eaab52681ff744701ecc7 | 55282737fc991f6a249b77e63c327af4d22fa3d4 | `config` should probably be passed to this function on line 85 of this file | Lucas-C | 80 |
posativ/isso | 800 | [MAJOR] js: Move to webpack, pug from r.js, jade | # Introduction
As already discussed in https://github.com/posativ/isso/issues/754, try to make Isso more maintainable by facilitating modern testing practices.
This PR is a bit massive, but trying to make `pug` or other updated deps play nice with RequireJs just for the sake of a clean history is not something I'm prepared to do.
So, here goes:
---
### js: Move to webpack, pug from r.js, jade
In the interest of maintainability and integration with other testing tools, get rid of `RequireJS` (sometimes also called `r.js` or `requirejs`)
This necessitates the following changes:
- Removing the `almond` (`AMD`) module loader (superseded by webpack internals)
- Removing `requirejs-text` for loading static resources (superseded by webpack `asset/source` loader)
- Removing `jade` templating engine (superseded by `pug`, which represents the original `jade` project that had to be renamed due to trademark issues)
`pug` v2+ no longer accepts `'mystr-{#foo.bar}'`-style variables inside attributes, so `*.pug` templates need to be changed accordingly (`mystr' + foo.bar`)
Note: templates have been moved to `templates/` directory and renamed from `.jade` to `.pug`.
- `jade-runtime` and accompanying shims (superseded by simply `pug-runtime`)
- Move `.svg` files inside own dir, simplify loading via `webpack`'s `asset/source`
- Add `webpack` config
- Add build scripts to `package.json`
- Adjust `Makefile` to use `webpack` via `npm run`
- Emit JS source map files from `webpack` (eases debugging)
- `.gitignore` JS source map files
While RequireJS utilized the following syntax:
```
define(["app/foo"], function(foo) {
var bar = doSomeStuff...
return bar;
})
```
Jest and other testing libraries need the NodeJS standard `CommonJS` style:
```
const foo = require("app/foo");
var bar = doSomeStuff...
module.exports = { bar };
```
Note: ES6/ECMAScript2015-style `import` has not been used since it would need transpilation via e.g. `babel` to be understood by Jest.
The RequireJS-style wrapping of all code inside `define({...})` caused everything to be indented by at least one level.
To keep the changes in this commit manageable, indentation will be removed in a later commit.
### isso: js: treewide: De-indent one level
Since switching from RequireJS to CommonJS syntax, the `define()` wrapper is no longer needed and as such, the the code formerly inside parentheses can be de-indented by one level.
### isso: js: i18: RequireJS to module.exports
(Just an extension of previous commit, to avoid touching too many files at once)
### demo: Use dev version of embed.js
This makes it easier to debug when testing. The demo shouldn't be user-facing, but either way, the performance penalty should be outweighed by debugging benefits.
### isso: js: Reduce deps for app/lib/
(Just a minor commit to make the following unit tests easier)
---
# Verifying
You can verify this commit by checking out this PR:
```sh
git clone https://github.com/posativ/isso isso
cd isso/
git fetch origin pull/800/head:pull-800
git checkout pull-800
```
And then installing everything as documented in [docs: Install from Source](https://posativ.org/isso/docs/install/#install-from-source).
Then, either embed Isso into your site or use the demo at [localhost:8080/demo](http://localhost:8080/demo)
---
A note for people from the future: You can use `git blame --ignore-rev=<sha>` to "ignore" the de-indent commits. See [A better git blame](https://www.michaelheap.com/git-ignore-rev/).
Note to myself: We can probably ditch the templates altogether and simply use plain html with javascript string interpolation. That way, we lose `pug`, `pug-loader` and `pug-runtime`, which would make the bundle significantly smaller. | null | 2022-02-19 16:30:50+00:00 | 2022-03-20 20:12:35+00:00 | isso/js/app/lib/identicons.js | /*
Copyright (C) 2013 Gregory Schier <gschier1990@gmail.com>
Copyright (C) 2013 Martin Zimmermann <info@posativ.org>
Inspired by http://codepen.io/gschier/pen/GLvAy
*/
define(["app/lib/promise", "app/config"], function(Q, config) {
"use strict";
// Number of squares width and height
var GRID = 5;
var pad = function(n, width) {
return n.length >= width ? n : new Array(width - n.length + 1).join("0") + n;
};
/**
* Fill in a square on the canvas.
*/
var fill = function(svg, x, y, padding, size, color) {
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", padding + x * size);
rect.setAttribute("y", padding + y * size);
rect.setAttribute("width", size);
rect.setAttribute("height", size);
rect.setAttribute("style", "fill: " + color);
svg.appendChild(rect);
};
/**
* Pick random squares to fill in.
*/
var generateIdenticon = function(key, padding, size) {
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("version", "1.1");
svg.setAttribute("viewBox", "0 0 " + size + " " + size);
svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
svg.setAttribute("shape-rendering", "crispEdges");
fill(svg, 0, 0, 0, size + 2*padding, config["avatar-bg"]);
if (typeof key === null) {
return svg;
}
Q.when(key, function(key) {
var hash = pad((parseInt(key.substr(-16), 16) % Math.pow(2, 18)).toString(2), 18),
index = 0;
svg.setAttribute("data-hash", key);
var i = parseInt(hash.substring(hash.length - 3, hash.length), 2),
color = config["avatar-fg"][i % config["avatar-fg"].length];
for (var x=0; x<Math.ceil(GRID/2); x++) {
for (var y=0; y<GRID; y++) {
if (hash.charAt(index) === "1") {
fill(svg, x, y, padding, 8, color);
// fill right sight symmetrically
if (x < Math.floor(GRID/2)) {
fill(svg, (GRID-1) - x, y, padding, 8, color);
}
}
index++;
}
}
});
return svg;
};
var generateBlank = function(height, width) {
var blank = parseInt([
0, 1, 1, 1, 1,
1, 0, 1, 1, 0,
1, 1, 1, 1, 1, /* purple: */ 0, 1, 0
].join(""), 2).toString(16);
var el = generateIdenticon(blank, height, width);
el.setAttribute("className", "blank"); // IE10 does not support classList on SVG elements, duh.
return el;
};
return {
generate: generateIdenticon,
blank: generateBlank
};
});
| /*
Copyright (C) 2013 Gregory Schier <gschier1990@gmail.com>
Copyright (C) 2013 Martin Zimmermann <info@posativ.org>
Inspired by http://codepen.io/gschier/pen/GLvAy
*/
const Q = require("app/lib/promise");
"use strict";
// Number of squares width and height
var GRID = 5;
var pad = function(n, width) {
return n.length >= width ? n : new Array(width - n.length + 1).join("0") + n;
};
/**
* Fill in a square on the canvas.
*/
var fill = function(svg, x, y, padding, size, color) {
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", padding + x * size);
rect.setAttribute("y", padding + y * size);
rect.setAttribute("width", size);
rect.setAttribute("height", size);
rect.setAttribute("style", "fill: " + color);
svg.appendChild(rect);
};
/**
* Pick random squares to fill in.
*/
var generateIdenticon = function(key, padding, size, config) {
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("version", "1.1");
svg.setAttribute("viewBox", "0 0 " + size + " " + size);
svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
svg.setAttribute("shape-rendering", "crispEdges");
fill(svg, 0, 0, 0, size + 2*padding, config["avatar-bg"]);
if (typeof key === null) {
return svg;
}
Q.when(key, function(key) {
var hash = pad((parseInt(key.substr(-16), 16) % Math.pow(2, 18)).toString(2), 18),
index = 0;
svg.setAttribute("data-hash", key);
var i = parseInt(hash.substring(hash.length - 3, hash.length), 2),
color = config["avatar-fg"][i % config["avatar-fg"].length];
for (var x=0; x<Math.ceil(GRID/2); x++) {
for (var y=0; y<GRID; y++) {
if (hash.charAt(index) === "1") {
fill(svg, x, y, padding, 8, color);
// fill right sight symmetrically
if (x < Math.floor(GRID/2)) {
fill(svg, (GRID-1) - x, y, padding, 8, color);
}
}
index++;
}
}
});
return svg;
};
/* TODO: This function is currently unused and should be removed */
var generateBlank = function(height, width, config) {
var blank = parseInt([
0, 1, 1, 1, 1,
1, 0, 1, 1, 0,
1, 1, 1, 1, 1, /* purple: */ 0, 1, 0
].join(""), 2).toString(16);
var el = generateIdenticon(blank, height, width, config);
el.setAttribute("className", "blank"); // IE10 does not support classList on SVG elements, duh.
return el;
};
module.exports = {
generate: generateIdenticon,
blank: generateBlank,
};
| ix5 | 4d7a05f22b4dd3fb870eaab52681ff744701ecc7 | 55282737fc991f6a249b77e63c327af4d22fa3d4 | In this particular instance you are right, but looking over this code again, it occurred to me that Isso currently doesn't use the `blank`/`generateBlank` functions at all.
I'll adjust this commit to let `generateBlank` use a passed `config` for the sake of keeping current functionality. | ix5 | 81 |
posativ/isso | 800 | [MAJOR] js: Move to webpack, pug from r.js, jade | # Introduction
As already discussed in https://github.com/posativ/isso/issues/754, try to make Isso more maintainable by facilitating modern testing practices.
This PR is a bit massive, but trying to make `pug` or other updated deps play nice with RequireJs just for the sake of a clean history is not something I'm prepared to do.
So, here goes:
---
### js: Move to webpack, pug from r.js, jade
In the interest of maintainability and integration with other testing tools, get rid of `RequireJS` (sometimes also called `r.js` or `requirejs`)
This necessitates the following changes:
- Removing the `almond` (`AMD`) module loader (superseded by webpack internals)
- Removing `requirejs-text` for loading static resources (superseded by webpack `asset/source` loader)
- Removing `jade` templating engine (superseded by `pug`, which represents the original `jade` project that had to be renamed due to trademark issues)
`pug` v2+ no longer accepts `'mystr-{#foo.bar}'`-style variables inside attributes, so `*.pug` templates need to be changed accordingly (`mystr' + foo.bar`)
Note: templates have been moved to `templates/` directory and renamed from `.jade` to `.pug`.
- `jade-runtime` and accompanying shims (superseded by simply `pug-runtime`)
- Move `.svg` files inside own dir, simplify loading via `webpack`'s `asset/source`
- Add `webpack` config
- Add build scripts to `package.json`
- Adjust `Makefile` to use `webpack` via `npm run`
- Emit JS source map files from `webpack` (eases debugging)
- `.gitignore` JS source map files
While RequireJS utilized the following syntax:
```
define(["app/foo"], function(foo) {
var bar = doSomeStuff...
return bar;
})
```
Jest and other testing libraries need the NodeJS standard `CommonJS` style:
```
const foo = require("app/foo");
var bar = doSomeStuff...
module.exports = { bar };
```
Note: ES6/ECMAScript2015-style `import` has not been used since it would need transpilation via e.g. `babel` to be understood by Jest.
The RequireJS-style wrapping of all code inside `define({...})` caused everything to be indented by at least one level.
To keep the changes in this commit manageable, indentation will be removed in a later commit.
### isso: js: treewide: De-indent one level
Since switching from RequireJS to CommonJS syntax, the `define()` wrapper is no longer needed and as such, the the code formerly inside parentheses can be de-indented by one level.
### isso: js: i18: RequireJS to module.exports
(Just an extension of previous commit, to avoid touching too many files at once)
### demo: Use dev version of embed.js
This makes it easier to debug when testing. The demo shouldn't be user-facing, but either way, the performance penalty should be outweighed by debugging benefits.
### isso: js: Reduce deps for app/lib/
(Just a minor commit to make the following unit tests easier)
---
# Verifying
You can verify this commit by checking out this PR:
```sh
git clone https://github.com/posativ/isso isso
cd isso/
git fetch origin pull/800/head:pull-800
git checkout pull-800
```
And then installing everything as documented in [docs: Install from Source](https://posativ.org/isso/docs/install/#install-from-source).
Then, either embed Isso into your site or use the demo at [localhost:8080/demo](http://localhost:8080/demo)
---
A note for people from the future: You can use `git blame --ignore-rev=<sha>` to "ignore" the de-indent commits. See [A better git blame](https://www.michaelheap.com/git-ignore-rev/).
Note to myself: We can probably ditch the templates altogether and simply use plain html with javascript string interpolation. That way, we lose `pug`, `pug-loader` and `pug-runtime`, which would make the bundle significantly smaller. | null | 2022-02-19 16:30:50+00:00 | 2022-03-20 20:12:35+00:00 | isso/js/app/lib/identicons.js | /*
Copyright (C) 2013 Gregory Schier <gschier1990@gmail.com>
Copyright (C) 2013 Martin Zimmermann <info@posativ.org>
Inspired by http://codepen.io/gschier/pen/GLvAy
*/
define(["app/lib/promise", "app/config"], function(Q, config) {
"use strict";
// Number of squares width and height
var GRID = 5;
var pad = function(n, width) {
return n.length >= width ? n : new Array(width - n.length + 1).join("0") + n;
};
/**
* Fill in a square on the canvas.
*/
var fill = function(svg, x, y, padding, size, color) {
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", padding + x * size);
rect.setAttribute("y", padding + y * size);
rect.setAttribute("width", size);
rect.setAttribute("height", size);
rect.setAttribute("style", "fill: " + color);
svg.appendChild(rect);
};
/**
* Pick random squares to fill in.
*/
var generateIdenticon = function(key, padding, size) {
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("version", "1.1");
svg.setAttribute("viewBox", "0 0 " + size + " " + size);
svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
svg.setAttribute("shape-rendering", "crispEdges");
fill(svg, 0, 0, 0, size + 2*padding, config["avatar-bg"]);
if (typeof key === null) {
return svg;
}
Q.when(key, function(key) {
var hash = pad((parseInt(key.substr(-16), 16) % Math.pow(2, 18)).toString(2), 18),
index = 0;
svg.setAttribute("data-hash", key);
var i = parseInt(hash.substring(hash.length - 3, hash.length), 2),
color = config["avatar-fg"][i % config["avatar-fg"].length];
for (var x=0; x<Math.ceil(GRID/2); x++) {
for (var y=0; y<GRID; y++) {
if (hash.charAt(index) === "1") {
fill(svg, x, y, padding, 8, color);
// fill right sight symmetrically
if (x < Math.floor(GRID/2)) {
fill(svg, (GRID-1) - x, y, padding, 8, color);
}
}
index++;
}
}
});
return svg;
};
var generateBlank = function(height, width) {
var blank = parseInt([
0, 1, 1, 1, 1,
1, 0, 1, 1, 0,
1, 1, 1, 1, 1, /* purple: */ 0, 1, 0
].join(""), 2).toString(16);
var el = generateIdenticon(blank, height, width);
el.setAttribute("className", "blank"); // IE10 does not support classList on SVG elements, duh.
return el;
};
return {
generate: generateIdenticon,
blank: generateBlank
};
});
| /*
Copyright (C) 2013 Gregory Schier <gschier1990@gmail.com>
Copyright (C) 2013 Martin Zimmermann <info@posativ.org>
Inspired by http://codepen.io/gschier/pen/GLvAy
*/
const Q = require("app/lib/promise");
"use strict";
// Number of squares width and height
var GRID = 5;
var pad = function(n, width) {
return n.length >= width ? n : new Array(width - n.length + 1).join("0") + n;
};
/**
* Fill in a square on the canvas.
*/
var fill = function(svg, x, y, padding, size, color) {
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", padding + x * size);
rect.setAttribute("y", padding + y * size);
rect.setAttribute("width", size);
rect.setAttribute("height", size);
rect.setAttribute("style", "fill: " + color);
svg.appendChild(rect);
};
/**
* Pick random squares to fill in.
*/
var generateIdenticon = function(key, padding, size, config) {
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("version", "1.1");
svg.setAttribute("viewBox", "0 0 " + size + " " + size);
svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
svg.setAttribute("shape-rendering", "crispEdges");
fill(svg, 0, 0, 0, size + 2*padding, config["avatar-bg"]);
if (typeof key === null) {
return svg;
}
Q.when(key, function(key) {
var hash = pad((parseInt(key.substr(-16), 16) % Math.pow(2, 18)).toString(2), 18),
index = 0;
svg.setAttribute("data-hash", key);
var i = parseInt(hash.substring(hash.length - 3, hash.length), 2),
color = config["avatar-fg"][i % config["avatar-fg"].length];
for (var x=0; x<Math.ceil(GRID/2); x++) {
for (var y=0; y<GRID; y++) {
if (hash.charAt(index) === "1") {
fill(svg, x, y, padding, 8, color);
// fill right sight symmetrically
if (x < Math.floor(GRID/2)) {
fill(svg, (GRID-1) - x, y, padding, 8, color);
}
}
index++;
}
}
});
return svg;
};
/* TODO: This function is currently unused and should be removed */
var generateBlank = function(height, width, config) {
var blank = parseInt([
0, 1, 1, 1, 1,
1, 0, 1, 1, 0,
1, 1, 1, 1, 1, /* purple: */ 0, 1, 0
].join(""), 2).toString(16);
var el = generateIdenticon(blank, height, width, config);
el.setAttribute("className", "blank"); // IE10 does not support classList on SVG elements, duh.
return el;
};
module.exports = {
generate: generateIdenticon,
blank: generateBlank,
};
| ix5 | 4d7a05f22b4dd3fb870eaab52681ff744701ecc7 | 55282737fc991f6a249b77e63c327af4d22fa3d4 | Done | ix5 | 82 |
posativ/isso | 764 | config: Disable interpolation of values | Do not attempt to use python string interpolation on values.
This is especially important for parsing passwords that might contain '%'
<strike>Strip single and double quotes from values. This might help with people who try to supply their admin password surrounded in quotes.</strike> (Edit: removed)
See: https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
Also adjust tests accordingly and add new test case for strings which should not be interpolated.
This avoids errors such as the following:
```
configparser.InterpolationSyntaxError:
'%' must be followed by '%' or '(', found: '%!...@c...!Cjq'
```
Fixes https://github.com/posativ/isso/issues/763
---
I also came across this while looking through the code:
treewide: Remove remaining py2 u-String usage
In python3, every string is a unicode string by default.
There is no need to keep the prefixed `u"mystring"`-style. | null | 2022-01-27 12:50:11+00:00 | 2022-02-01 10:32:02+00:00 | isso/config.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* parse human-readable timedelta such as "15m" as "15 minutes"
* handle indented lines as "lists"
"""
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser(allow_no_value=True)
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* Parse human-readable timedelta such as "15m" as "15 minutes"
* Handle indented lines as "lists"
* Disable string interpolation ('%s') for values
"""
def __init__(self, *args, **kwargs):
"""Supply modified defaults to configparser.ConfigParser
https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
allow_no_value=True: Allow empty config keys
interpolation=None: Do not attempt to use python string interpolation on
values. This is especially important for parsing
passwords that might contain '%'
"""
return super(IssoParser, self).__init__(
allow_no_value=True, interpolation=None, *args, **kwargs)
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser()
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| ix5 | abe0a9a511c05ca6d3fa3ef1c499fd98085f30e9 | 7d47825a2a13830c75bff77ed74f992d1030df71 | Note that I moved the `allow_no_value` arg into the `__init__` function to make it easier to keep things in sync. Otherwise you'd have to adjust the tests as well every time `IssoParser` needs new args. | ix5 | 83 |
posativ/isso | 764 | config: Disable interpolation of values | Do not attempt to use python string interpolation on values.
This is especially important for parsing passwords that might contain '%'
<strike>Strip single and double quotes from values. This might help with people who try to supply their admin password surrounded in quotes.</strike> (Edit: removed)
See: https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
Also adjust tests accordingly and add new test case for strings which should not be interpolated.
This avoids errors such as the following:
```
configparser.InterpolationSyntaxError:
'%' must be followed by '%' or '(', found: '%!...@c...!Cjq'
```
Fixes https://github.com/posativ/isso/issues/763
---
I also came across this while looking through the code:
treewide: Remove remaining py2 u-String usage
In python3, every string is a unicode string by default.
There is no need to keep the prefixed `u"mystring"`-style. | null | 2022-01-27 12:50:11+00:00 | 2022-02-01 10:32:02+00:00 | isso/config.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* parse human-readable timedelta such as "15m" as "15 minutes"
* handle indented lines as "lists"
"""
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser(allow_no_value=True)
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* Parse human-readable timedelta such as "15m" as "15 minutes"
* Handle indented lines as "lists"
* Disable string interpolation ('%s') for values
"""
def __init__(self, *args, **kwargs):
"""Supply modified defaults to configparser.ConfigParser
https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
allow_no_value=True: Allow empty config keys
interpolation=None: Do not attempt to use python string interpolation on
values. This is especially important for parsing
passwords that might contain '%'
"""
return super(IssoParser, self).__init__(
allow_no_value=True, interpolation=None, *args, **kwargs)
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser()
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| ix5 | abe0a9a511c05ca6d3fa3ef1c499fd98085f30e9 | 7d47825a2a13830c75bff77ed74f992d1030df71 | Not a fan of this since it's not strictly needed any actually disallows passwords starting or ending with these characters (in addition to whitespace that may actually be gobbled up by the ini parser) | stefangehn | 84 |
posativ/isso | 764 | config: Disable interpolation of values | Do not attempt to use python string interpolation on values.
This is especially important for parsing passwords that might contain '%'
<strike>Strip single and double quotes from values. This might help with people who try to supply their admin password surrounded in quotes.</strike> (Edit: removed)
See: https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
Also adjust tests accordingly and add new test case for strings which should not be interpolated.
This avoids errors such as the following:
```
configparser.InterpolationSyntaxError:
'%' must be followed by '%' or '(', found: '%!...@c...!Cjq'
```
Fixes https://github.com/posativ/isso/issues/763
---
I also came across this while looking through the code:
treewide: Remove remaining py2 u-String usage
In python3, every string is a unicode string by default.
There is no need to keep the prefixed `u"mystring"`-style. | null | 2022-01-27 12:50:11+00:00 | 2022-02-01 10:32:02+00:00 | isso/config.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* parse human-readable timedelta such as "15m" as "15 minutes"
* handle indented lines as "lists"
"""
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser(allow_no_value=True)
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* Parse human-readable timedelta such as "15m" as "15 minutes"
* Handle indented lines as "lists"
* Disable string interpolation ('%s') for values
"""
def __init__(self, *args, **kwargs):
"""Supply modified defaults to configparser.ConfigParser
https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
allow_no_value=True: Allow empty config keys
interpolation=None: Do not attempt to use python string interpolation on
values. This is especially important for parsing
passwords that might contain '%'
"""
return super(IssoParser, self).__init__(
allow_no_value=True, interpolation=None, *args, **kwargs)
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser()
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| ix5 | abe0a9a511c05ca6d3fa3ef1c499fd98085f30e9 | 7d47825a2a13830c75bff77ed74f992d1030df71 | strip can be passed multiple chars to strip off a string, no need to call it twice | stefangehn | 85 |
posativ/isso | 764 | config: Disable interpolation of values | Do not attempt to use python string interpolation on values.
This is especially important for parsing passwords that might contain '%'
<strike>Strip single and double quotes from values. This might help with people who try to supply their admin password surrounded in quotes.</strike> (Edit: removed)
See: https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
Also adjust tests accordingly and add new test case for strings which should not be interpolated.
This avoids errors such as the following:
```
configparser.InterpolationSyntaxError:
'%' must be followed by '%' or '(', found: '%!...@c...!Cjq'
```
Fixes https://github.com/posativ/isso/issues/763
---
I also came across this while looking through the code:
treewide: Remove remaining py2 u-String usage
In python3, every string is a unicode string by default.
There is no need to keep the prefixed `u"mystring"`-style. | null | 2022-01-27 12:50:11+00:00 | 2022-02-01 10:32:02+00:00 | isso/config.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* parse human-readable timedelta such as "15m" as "15 minutes"
* handle indented lines as "lists"
"""
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser(allow_no_value=True)
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* Parse human-readable timedelta such as "15m" as "15 minutes"
* Handle indented lines as "lists"
* Disable string interpolation ('%s') for values
"""
def __init__(self, *args, **kwargs):
"""Supply modified defaults to configparser.ConfigParser
https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
allow_no_value=True: Allow empty config keys
interpolation=None: Do not attempt to use python string interpolation on
values. This is especially important for parsing
passwords that might contain '%'
"""
return super(IssoParser, self).__init__(
allow_no_value=True, interpolation=None, *args, **kwargs)
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser()
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| ix5 | abe0a9a511c05ca6d3fa3ef1c499fd98085f30e9 | 7d47825a2a13830c75bff77ed74f992d1030df71 | +1 | jelmer | 86 |
posativ/isso | 764 | config: Disable interpolation of values | Do not attempt to use python string interpolation on values.
This is especially important for parsing passwords that might contain '%'
<strike>Strip single and double quotes from values. This might help with people who try to supply their admin password surrounded in quotes.</strike> (Edit: removed)
See: https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
Also adjust tests accordingly and add new test case for strings which should not be interpolated.
This avoids errors such as the following:
```
configparser.InterpolationSyntaxError:
'%' must be followed by '%' or '(', found: '%!...@c...!Cjq'
```
Fixes https://github.com/posativ/isso/issues/763
---
I also came across this while looking through the code:
treewide: Remove remaining py2 u-String usage
In python3, every string is a unicode string by default.
There is no need to keep the prefixed `u"mystring"`-style. | null | 2022-01-27 12:50:11+00:00 | 2022-02-01 10:32:02+00:00 | isso/config.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* parse human-readable timedelta such as "15m" as "15 minutes"
* handle indented lines as "lists"
"""
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser(allow_no_value=True)
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* Parse human-readable timedelta such as "15m" as "15 minutes"
* Handle indented lines as "lists"
* Disable string interpolation ('%s') for values
"""
def __init__(self, *args, **kwargs):
"""Supply modified defaults to configparser.ConfigParser
https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
allow_no_value=True: Allow empty config keys
interpolation=None: Do not attempt to use python string interpolation on
values. This is especially important for parsing
passwords that might contain '%'
"""
return super(IssoParser, self).__init__(
allow_no_value=True, interpolation=None, *args, **kwargs)
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser()
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| ix5 | abe0a9a511c05ca6d3fa3ef1c499fd98085f30e9 | 7d47825a2a13830c75bff77ed74f992d1030df71 | Why do we need to strip these? It seems like it would make it impossible to actually use these characters at the beginning and end of strings. | jelmer | 87 |
posativ/isso | 764 | config: Disable interpolation of values | Do not attempt to use python string interpolation on values.
This is especially important for parsing passwords that might contain '%'
<strike>Strip single and double quotes from values. This might help with people who try to supply their admin password surrounded in quotes.</strike> (Edit: removed)
See: https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
Also adjust tests accordingly and add new test case for strings which should not be interpolated.
This avoids errors such as the following:
```
configparser.InterpolationSyntaxError:
'%' must be followed by '%' or '(', found: '%!...@c...!Cjq'
```
Fixes https://github.com/posativ/isso/issues/763
---
I also came across this while looking through the code:
treewide: Remove remaining py2 u-String usage
In python3, every string is a unicode string by default.
There is no need to keep the prefixed `u"mystring"`-style. | null | 2022-01-27 12:50:11+00:00 | 2022-02-01 10:32:02+00:00 | isso/config.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* parse human-readable timedelta such as "15m" as "15 minutes"
* handle indented lines as "lists"
"""
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser(allow_no_value=True)
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* Parse human-readable timedelta such as "15m" as "15 minutes"
* Handle indented lines as "lists"
* Disable string interpolation ('%s') for values
"""
def __init__(self, *args, **kwargs):
"""Supply modified defaults to configparser.ConfigParser
https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
allow_no_value=True: Allow empty config keys
interpolation=None: Do not attempt to use python string interpolation on
values. This is especially important for parsing
passwords that might contain '%'
"""
return super(IssoParser, self).__init__(
allow_no_value=True, interpolation=None, *args, **kwargs)
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser()
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| ix5 | abe0a9a511c05ca6d3fa3ef1c499fd98085f30e9 | 7d47825a2a13830c75bff77ed74f992d1030df71 | Alright, thank you for your input! Adjusted accordingly. | ix5 | 88 |
posativ/isso | 764 | config: Disable interpolation of values | Do not attempt to use python string interpolation on values.
This is especially important for parsing passwords that might contain '%'
<strike>Strip single and double quotes from values. This might help with people who try to supply their admin password surrounded in quotes.</strike> (Edit: removed)
See: https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
Also adjust tests accordingly and add new test case for strings which should not be interpolated.
This avoids errors such as the following:
```
configparser.InterpolationSyntaxError:
'%' must be followed by '%' or '(', found: '%!...@c...!Cjq'
```
Fixes https://github.com/posativ/isso/issues/763
---
I also came across this while looking through the code:
treewide: Remove remaining py2 u-String usage
In python3, every string is a unicode string by default.
There is no need to keep the prefixed `u"mystring"`-style. | null | 2022-01-27 12:50:11+00:00 | 2022-02-01 10:32:02+00:00 | isso/config.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* parse human-readable timedelta such as "15m" as "15 minutes"
* handle indented lines as "lists"
"""
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser(allow_no_value=True)
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import re
import logging
import datetime
from email.utils import parseaddr, formataddr
from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError
logger = logging.getLogger("isso")
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days, 0:00:00
>>> print(timedelta("3w 12h 57m"))
21 days, 12:57:00
>>> print(timedelta("1h30m37s"))
1:30:37
>>> print(timedelta("1asdf3w"))
Traceback (most recent call last):
...
ValueError: invalid human-readable timedelta
"""
keys = ["weeks", "days", "hours", "minutes", "seconds"]
regex = "".join(["((?P<%s>\\d+)%s ?)?" % (k, k[0]) for k in keys])
kwargs = {}
for k, v in re.match(regex, string).groupdict(default="0").items():
kwargs[k] = int(v)
rv = datetime.timedelta(**kwargs)
if rv == datetime.timedelta():
raise ValueError("invalid human-readable timedelta")
return datetime.timedelta(**kwargs)
class Section(object):
"""A wrapper around :class:`IssoParser` that returns a partial configuration
section object.
>>> conf = new({"foo": {"bar": "spam"}})
>>> section = conf.section("foo")
>>> conf.get("foo", "bar") == section.get("bar")
True
"""
def __init__(self, conf, section):
self.conf = conf
self.section = section
def get(self, key):
return self.conf.get(self.section, key)
def getint(self, key):
return self.conf.getint(self.section, key)
def getlist(self, key):
return self.conf.getlist(self.section, key)
def getiter(self, key):
return self.conf.getiter(self.section, key)
def getboolean(self, key):
return self.conf.getboolean(self.section, key)
class IssoParser(ConfigParser):
"""Parse INI-style configuration with some modifications for Isso.
* Parse human-readable timedelta such as "15m" as "15 minutes"
* Handle indented lines as "lists"
* Disable string interpolation ('%s') for values
"""
def __init__(self, *args, **kwargs):
"""Supply modified defaults to configparser.ConfigParser
https://docs.python.org/3.9/library/configparser.html#configparser.ConfigParser
allow_no_value=True: Allow empty config keys
interpolation=None: Do not attempt to use python string interpolation on
values. This is especially important for parsing
passwords that might contain '%'
"""
return super(IssoParser, self).__init__(
allow_no_value=True, interpolation=None, *args, **kwargs)
def getint(self, section, key):
try:
delta = timedelta(self.get(section, key))
except ValueError:
return super(IssoParser, self).getint(section, key)
else:
try:
return int(delta.total_seconds())
except AttributeError:
return int(delta.total_seconds())
def getlist(self, section, key):
return list(map(str.strip, self.get(section, key).split(',')))
def getiter(self, section, key):
for item in map(str.strip, self.get(section, key).split('\n')):
if item:
yield item
def section(self, section):
return Section(self, section)
def new(options=None):
cp = IssoParser()
if options:
cp.read_dict(options)
return cp
def load(default, user=None):
# return set of (section, option)
def setify(cp):
return set((section, option) for section in cp.sections()
for option in cp.options(section))
parser = new()
with open(default, 'r') as f:
parser.read_file(f)
a = setify(parser)
if user:
with open(user, 'r') as f:
parser.read_file(f)
for item in setify(parser).difference(a):
logger.warn("no such option: [%s] %s", *item)
if item in (("server", "host"), ("server", "port")):
logger.warn("use `listen = http://$host:$port` instead")
if item == ("smtp", "ssl"):
logger.warn("use `security = none | starttls | ssl` instead")
if item == ("general", "session-key"):
logger.info("Your `session-key` has been stored in the "
"database itself, this option is now unused")
try:
parser.add_section('smtp')
except DuplicateSectionError:
pass
try:
fromaddr = parser.get("smtp", "from")
except (NoOptionError, NoSectionError):
fromaddr = ''
if not parseaddr(fromaddr)[0]:
parser.set("smtp", "from",
formataddr(("Ich schrei sonst!", fromaddr)))
return parser
| ix5 | abe0a9a511c05ca6d3fa3ef1c499fd98085f30e9 | 7d47825a2a13830c75bff77ed74f992d1030df71 | See above. | ix5 | 89 |
posativ/isso | 704 | Serve isso.css separately instead of inline | Instead of embedding isso.css inside the client javascript (which required an `style-src: unsafe-inline` CSP), fetch isso.css from `api.endpoint+"/css/isso.css"`.
Allow clients to override fetch location using `data-isso-css-url="https://comments.example.org/css/isso.css"`
Note: No modification needed for packaging since isso.css is already included via MANIFEST.in.
Fixes https://github.com/posativ/isso/issues/584 | null | 2021-02-07 10:00:36+00:00 | 2021-03-22 22:29:43+00:00 | docs/docs/configuration/client.rst | Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-lang="ru"
data-isso-reply-to-self="false"
data-isso-require-author="false"
data-isso-require-email="false"
data-isso-reply-notifications="false"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
``data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"``
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
Lazy-loading on scroll
----------------------
You can defer loading the ``embed.min.js`` script until the user has scrolled
to the bottom of the page:
.. code-block:: html
<script type="text/javascript">
// Lazy-load isso only when page end is in view
function loadIsso() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "/prefix/js/embed.min.js");
// add relevant data-isso attributes here
script.setAttribute("data-isso", "/prefix/");
document.getElementsByTagName("head")[0].appendChild(script);
}
let offset = 50; // Start loading 50px before reaching bottom
function scrollBottomListener(ev) {
if ((window.scrollY + window.innerHeight)
>= (document.documentElement.scrollHeight - offset)) {
loadIsso();
window.removeEventListener('scroll', scrollBottomListener);
}
}
window.onload = function() {
// If viewport >= page height, load immediately
if ((window.scrollY + window.innerHeight)
>= (document.documentElement.scrollHeight - offset)) {
loadIsso();
} else {
window.addEventListener('scroll', scrollBottomListener);
}
}
</script>
*Note that loading additional content only after user interaction is bad for
SEO. Additionally, users could experience a "jank" effect.*
Use lazy-loading only if you are desperately trying to save bandwidth. By
specifying ``async`` in the ``<script`` tag, loading the Isso Javascript will
not render-block anyway.
data-isso
---------
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css
-------------
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
--------------
Override useragent's preferred language. Isso has been translated in over 12
languages. The language is configured by its `ISO 639-1
<https://en.wikipedia.org/wiki/ISO_639-1>`_ (two letter) code.
You find a list of all supported languages on `GitHub
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_.
data-isso-reply-to-self
-----------------------
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
------------------------
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
-----------------------
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
-----------------------------
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-max-comments-top and data-isso-max-comments-nested
------------------------------------------------------------
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to `"inf"` to show all, or `"0"` to hide all.
data-isso-reveal-on-click
-------------------------
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
----------------
Enable or disable avatar generation.
data-isso-avatar-bg
-------------------
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
-------------------
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-gravatar
------------------
Uses gravatar images instead of generating svg images. You have to set
"data-isso-avatar" to **false** when you want to use this. Otherwise
both the gravatar and avatar svg image will show up. Please also set
option "gravatar" to **true** in the server configuration...
data-isso-vote
--------------
Enable or disable voting feature on the client side.
data-isso-vote-levels
---------------------
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
--------------
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
| Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-reply-to-self="false"
data-isso-require-author="false"
data-isso-require-email="false"
data-isso-reply-notifications="false"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
``data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"``
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
Lazy-loading on scroll
----------------------
You can defer loading the ``embed.min.js`` script until the user has scrolled
to the bottom of the page:
.. code-block:: html
<script type="text/javascript">
// Lazy-load isso only when page end is in view
function loadIsso() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "/prefix/js/embed.min.js");
// add relevant data-isso attributes here
script.setAttribute("data-isso", "/prefix/");
document.getElementsByTagName("head")[0].appendChild(script);
}
let offset = 50; // Start loading 50px before reaching bottom
function scrollBottomListener(ev) {
if ((window.scrollY + window.innerHeight)
>= (document.documentElement.scrollHeight - offset)) {
loadIsso();
window.removeEventListener('scroll', scrollBottomListener);
}
}
window.onload = function() {
// If viewport >= page height, load immediately
if ((window.scrollY + window.innerHeight)
>= (document.documentElement.scrollHeight - offset)) {
loadIsso();
} else {
window.addEventListener('scroll', scrollBottomListener);
}
}
</script>
*Note that loading additional content only after user interaction is bad for
SEO. Additionally, users could experience a "jank" effect.*
Use lazy-loading only if you are desperately trying to save bandwidth. By
specifying ``async`` in the ``<script`` tag, loading the Isso Javascript will
not render-block anyway.
data-isso
---------
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
-----------------
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
-------------
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
--------------
Override useragent's preferred language. Isso has been translated in over 12
languages. The language is configured by its `ISO 639-1
<https://en.wikipedia.org/wiki/ISO_639-1>`_ (two letter) code.
You find a list of all supported languages on `GitHub
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_.
data-isso-reply-to-self
-----------------------
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
------------------------
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
-----------------------
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
-----------------------------
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-max-comments-top and data-isso-max-comments-nested
------------------------------------------------------------
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to `"inf"` to show all, or `"0"` to hide all.
data-isso-reveal-on-click
-------------------------
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
----------------
Enable or disable avatar generation.
data-isso-avatar-bg
-------------------
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
-------------------
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-gravatar
------------------
Uses gravatar images instead of generating svg images. You have to set
"data-isso-avatar" to **false** when you want to use this. Otherwise
both the gravatar and avatar svg image will show up. Please also set
option "gravatar" to **true** in the server configuration...
data-isso-vote
--------------
Enable or disable voting feature on the client side.
data-isso-vote-levels
---------------------
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
--------------
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
| ix5 | c73694959a2beea27debb2c4001e9a593d58f270 | a7c1069cf5feab721a166e7796ce725287a46189 | I guess this block was put at the wrong place. The text above this heading is for the attribute data-isso-css-url. Mind to move it below? | MorrisJobke | 90 |
posativ/isso | 704 | Serve isso.css separately instead of inline | Instead of embedding isso.css inside the client javascript (which required an `style-src: unsafe-inline` CSP), fetch isso.css from `api.endpoint+"/css/isso.css"`.
Allow clients to override fetch location using `data-isso-css-url="https://comments.example.org/css/isso.css"`
Note: No modification needed for packaging since isso.css is already included via MANIFEST.in.
Fixes https://github.com/posativ/isso/issues/584 | null | 2021-02-07 10:00:36+00:00 | 2021-03-22 22:29:43+00:00 | docs/docs/configuration/client.rst | Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-lang="ru"
data-isso-reply-to-self="false"
data-isso-require-author="false"
data-isso-require-email="false"
data-isso-reply-notifications="false"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
``data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"``
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
Lazy-loading on scroll
----------------------
You can defer loading the ``embed.min.js`` script until the user has scrolled
to the bottom of the page:
.. code-block:: html
<script type="text/javascript">
// Lazy-load isso only when page end is in view
function loadIsso() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "/prefix/js/embed.min.js");
// add relevant data-isso attributes here
script.setAttribute("data-isso", "/prefix/");
document.getElementsByTagName("head")[0].appendChild(script);
}
let offset = 50; // Start loading 50px before reaching bottom
function scrollBottomListener(ev) {
if ((window.scrollY + window.innerHeight)
>= (document.documentElement.scrollHeight - offset)) {
loadIsso();
window.removeEventListener('scroll', scrollBottomListener);
}
}
window.onload = function() {
// If viewport >= page height, load immediately
if ((window.scrollY + window.innerHeight)
>= (document.documentElement.scrollHeight - offset)) {
loadIsso();
} else {
window.addEventListener('scroll', scrollBottomListener);
}
}
</script>
*Note that loading additional content only after user interaction is bad for
SEO. Additionally, users could experience a "jank" effect.*
Use lazy-loading only if you are desperately trying to save bandwidth. By
specifying ``async`` in the ``<script`` tag, loading the Isso Javascript will
not render-block anyway.
data-isso
---------
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css
-------------
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
--------------
Override useragent's preferred language. Isso has been translated in over 12
languages. The language is configured by its `ISO 639-1
<https://en.wikipedia.org/wiki/ISO_639-1>`_ (two letter) code.
You find a list of all supported languages on `GitHub
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_.
data-isso-reply-to-self
-----------------------
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
------------------------
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
-----------------------
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
-----------------------------
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-max-comments-top and data-isso-max-comments-nested
------------------------------------------------------------
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to `"inf"` to show all, or `"0"` to hide all.
data-isso-reveal-on-click
-------------------------
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
----------------
Enable or disable avatar generation.
data-isso-avatar-bg
-------------------
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
-------------------
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-gravatar
------------------
Uses gravatar images instead of generating svg images. You have to set
"data-isso-avatar" to **false** when you want to use this. Otherwise
both the gravatar and avatar svg image will show up. Please also set
option "gravatar" to **true** in the server configuration...
data-isso-vote
--------------
Enable or disable voting feature on the client side.
data-isso-vote-levels
---------------------
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
--------------
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
| Client Configuration
====================
You can configure the client (the JS part) with custom data attributes,
preferably in the script tag which embeds the JS:
.. code-block:: html
<script data-isso="/prefix/"
data-isso-id="thread-id"
data-isso-css="true"
data-isso-css-url="null"
data-isso-lang="ru"
data-isso-reply-to-self="false"
data-isso-require-author="false"
data-isso-require-email="false"
data-isso-reply-notifications="false"
data-isso-max-comments-top="10"
data-isso-max-comments-nested="5"
data-isso-reveal-on-click="5"
data-isso-avatar="true"
data-isso-avatar-bg="#f0f0f0"
data-isso-avatar-fg="#9abf88 #5698c4 #e279a3 #9163b6 ..."
data-isso-vote="true"
data-isso-vote-levels=""
data-isso-feed="false"
src="/prefix/js/embed.js"></script>
Furthermore you can override the automatic title detection inside
the embed tag, as well as the thread ID, e.g.:
.. code-block:: html
<section id="isso-thread" data-title="Foo!" data-isso-id="/path/to/resource"></section>
Additionally, you can override any translation string for any language by adding
a ``data-isso-`` attribute that is equal to the translation key (found `here`__) with
``-text-[lang]`` appended to it. So, for example, if you want to override the
english translation of the ``postbox-notification`` message, you could add:
``data-isso-postbox-notification-text-en="Select to be notified of replies to your comment"``
.. __: https://github.com/posativ/isso/blob/master/isso/js/app/i18n/en.js
Lazy-loading on scroll
----------------------
You can defer loading the ``embed.min.js`` script until the user has scrolled
to the bottom of the page:
.. code-block:: html
<script type="text/javascript">
// Lazy-load isso only when page end is in view
function loadIsso() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "/prefix/js/embed.min.js");
// add relevant data-isso attributes here
script.setAttribute("data-isso", "/prefix/");
document.getElementsByTagName("head")[0].appendChild(script);
}
let offset = 50; // Start loading 50px before reaching bottom
function scrollBottomListener(ev) {
if ((window.scrollY + window.innerHeight)
>= (document.documentElement.scrollHeight - offset)) {
loadIsso();
window.removeEventListener('scroll', scrollBottomListener);
}
}
window.onload = function() {
// If viewport >= page height, load immediately
if ((window.scrollY + window.innerHeight)
>= (document.documentElement.scrollHeight - offset)) {
loadIsso();
} else {
window.addEventListener('scroll', scrollBottomListener);
}
}
</script>
*Note that loading additional content only after user interaction is bad for
SEO. Additionally, users could experience a "jank" effect.*
Use lazy-loading only if you are desperately trying to save bandwidth. By
specifying ``async`` in the ``<script`` tag, loading the Isso Javascript will
not render-block anyway.
data-isso
---------
Isso usually detects the REST API automatically, but when you serve the JS
script on a different location, this may fail. Use `data-isso` to
override the API location:
.. code-block:: html
<script data-isso="/isso" src="/path/to/embed.min.js"></script>
data-isso-css-url
-----------------
Set URL from which to fetch ``isso.css``, e.g. from a CDN.
Defaults to fetching from the API endpoint.
.. code-block:: html
<script src="..." data-isso-css-url="/path/to/isso.css"></script>
data-isso-css
-------------
Set to `false` prevents Isso from automatically appending the stylesheet.
Defaults to `true`.
.. code-block:: html
<script src="..." data-isso-css="false"></script>
data-isso-lang
--------------
Override useragent's preferred language. Isso has been translated in over 12
languages. The language is configured by its `ISO 639-1
<https://en.wikipedia.org/wiki/ISO_639-1>`_ (two letter) code.
You find a list of all supported languages on `GitHub
<https://github.com/posativ/isso/tree/master/isso/js/app/i18n>`_.
data-isso-reply-to-self
-----------------------
Set to `true` when spam guard is configured with `reply-to-self = true`.
data-isso-require-author
------------------------
Set to `true` when spam guard is configured with `require-author = true`.
data-isso-require-email
-----------------------
Set to `true` when spam guard is configured with `require-email = true`.
data-isso-reply-notifications
-----------------------------
Set to `true` when reply notifications is configured with `reply-notifications = true`.
data-isso-max-comments-top and data-isso-max-comments-nested
------------------------------------------------------------
Number of top level (or nested) comments to show by default. If some
comments are not shown, an "X Hidden" link is shown.
Set to `"inf"` to show all, or `"0"` to hide all.
data-isso-reveal-on-click
-------------------------
Number of comments to reveal on clicking the "X Hidden" link.
data-isso-avatar
----------------
Enable or disable avatar generation.
data-isso-avatar-bg
-------------------
Set avatar background color. Any valid CSS color will do.
data-isso-avatar-fg
-------------------
Set avatar foreground color. Up to 8 colors are possible. The default color
scheme is based in `this color palette <http://colrd.com/palette/19308/>`_.
Multiple colors must be separated by space. If you use less than eight colors
and not a multiple of 2, the color distribution is not even.
data-isso-gravatar
------------------
Uses gravatar images instead of generating svg images. You have to set
"data-isso-avatar" to **false** when you want to use this. Otherwise
both the gravatar and avatar svg image will show up. Please also set
option "gravatar" to **true** in the server configuration...
data-isso-vote
--------------
Enable or disable voting feature on the client side.
data-isso-vote-levels
---------------------
List of vote levels used to customize comment appearance based on score.
Provide a comma-separated values (eg. `"0,5,10,25,100"`) or a JSON array (eg. `"[-5,5,15]"`).
For example, the value `"-5,5"` will cause each `isso-comment` to be given one of these 3 classes:
- `isso-vote-level-0` for scores lower than `-5`
- `isso-vote-level-1` for scores between `-5` and `4`
- `isso-vote-level-2` for scores of `5` and greater
These classes can then be used to customize the appearance of comments (eg. put a star on popular comments)
data-isso-feed
--------------
Enable or disable the addition of a link to the feed for the comment
thread. The link will only be valid if the appropriate setting, in
``[rss]`` section, is also enabled server-side.
| ix5 | c73694959a2beea27debb2c4001e9a593d58f270 | a7c1069cf5feab721a166e7796ce725287a46189 | Thanks for catching this! Fixed. | ix5 | 91 |
posativ/isso | 703 | docs: install: Reorder Install from source, py3.5 | Reorder steps so that js files are generated before `python setup.py develop`.
Clarify that isso should be installed in editable mode when installed from source.
Clarify that sphinx is needed for docs, and only for docs.
Clarify that npm is definitely required.
Isso requires python 3.5 now. | null | 2021-02-05 09:16:57+00:00 | 2021-12-24 01:58:20+00:00 | docs/docs/install.rst | Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 2.7 or 3.4+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *for frontend*
- `sassc <https://github.com/sass/sassc>`_ for compiling
`.scss <https://sass-lang.com/>`_ - *for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `install`
~> isso run
Install JavaScript modules:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 3.5+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *required for frontend*
- `sphinx <http://www.sphinx-doc.org/>`_,
`sassc <https://github.com/sass/sassc>`_ (for compiling
`.scss <https://sass-lang.com/>`_ to css) - *optional - only for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install JavaScript modules using ``npm``:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `pip install -e .`
~> isso run
Install `sphinx <http://www.sphinx-doc.org/>`_ for generating docs:
.. code-block:: sh
~> pip install sphinx
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| ix5 | fb6f731f6bcbb871f5b3632843a09d2ed501a596 | 28beb7e848db5ce0e89f8a63e929ecaca4dcf529 | I don't follow this; this does include generated files (including locally changed ones), and I use it regularly. | jelmer | 92 |
posativ/isso | 703 | docs: install: Reorder Install from source, py3.5 | Reorder steps so that js files are generated before `python setup.py develop`.
Clarify that isso should be installed in editable mode when installed from source.
Clarify that sphinx is needed for docs, and only for docs.
Clarify that npm is definitely required.
Isso requires python 3.5 now. | null | 2021-02-05 09:16:57+00:00 | 2021-12-24 01:58:20+00:00 | docs/docs/install.rst | Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 2.7 or 3.4+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *for frontend*
- `sassc <https://github.com/sass/sassc>`_ for compiling
`.scss <https://sass-lang.com/>`_ - *for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `install`
~> isso run
Install JavaScript modules:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 3.5+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *required for frontend*
- `sphinx <http://www.sphinx-doc.org/>`_,
`sassc <https://github.com/sass/sassc>`_ (for compiling
`.scss <https://sass-lang.com/>`_ to css) - *optional - only for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install JavaScript modules using ``npm``:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `pip install -e .`
~> isso run
Install `sphinx <http://www.sphinx-doc.org/>`_ for generating docs:
.. code-block:: sh
~> pip install sphinx
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| ix5 | fb6f731f6bcbb871f5b3632843a09d2ed501a596 | 28beb7e848db5ce0e89f8a63e929ecaca4dcf529 | Unfortunate wording on my part.
If isso is installed using `python setup.py install`, the isso artifact files will be copied to `<venv>/lib/python3.9/site-packages/isso-0.12.4-py3.9.egg/isso/`, but any changes you make from now on will not be carried over to the site-packages isso, unless you run the install command again.
Maybe others have better suggestions for the wording? What I want to strongly communicate is that the editable install option will save many from annoying misunderstandings and outdated files. | ix5 | 93 |
posativ/isso | 703 | docs: install: Reorder Install from source, py3.5 | Reorder steps so that js files are generated before `python setup.py develop`.
Clarify that isso should be installed in editable mode when installed from source.
Clarify that sphinx is needed for docs, and only for docs.
Clarify that npm is definitely required.
Isso requires python 3.5 now. | null | 2021-02-05 09:16:57+00:00 | 2021-12-24 01:58:20+00:00 | docs/docs/install.rst | Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 2.7 or 3.4+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *for frontend*
- `sassc <https://github.com/sass/sassc>`_ for compiling
`.scss <https://sass-lang.com/>`_ - *for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `install`
~> isso run
Install JavaScript modules:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 3.5+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *required for frontend*
- `sphinx <http://www.sphinx-doc.org/>`_,
`sassc <https://github.com/sass/sassc>`_ (for compiling
`.scss <https://sass-lang.com/>`_ to css) - *optional - only for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install JavaScript modules using ``npm``:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `pip install -e .`
~> isso run
Install `sphinx <http://www.sphinx-doc.org/>`_ for generating docs:
.. code-block:: sh
~> pip install sphinx
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| ix5 | fb6f731f6bcbb871f5b3632843a09d2ed501a596 | 28beb7e848db5ce0e89f8a63e929ecaca4dcf529 | I think this is quite subjective - I don't use venv, and "python install" is how I deploy isso. Perhaps just drop this note altogether? Alternative, just add a caution here about "setup.py install" and venv. | jelmer | 94 |
posativ/isso | 703 | docs: install: Reorder Install from source, py3.5 | Reorder steps so that js files are generated before `python setup.py develop`.
Clarify that isso should be installed in editable mode when installed from source.
Clarify that sphinx is needed for docs, and only for docs.
Clarify that npm is definitely required.
Isso requires python 3.5 now. | null | 2021-02-05 09:16:57+00:00 | 2021-12-24 01:58:20+00:00 | docs/docs/install.rst | Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 2.7 or 3.4+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *for frontend*
- `sassc <https://github.com/sass/sassc>`_ for compiling
`.scss <https://sass-lang.com/>`_ - *for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `install`
~> isso run
Install JavaScript modules:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 3.5+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *required for frontend*
- `sphinx <http://www.sphinx-doc.org/>`_,
`sassc <https://github.com/sass/sassc>`_ (for compiling
`.scss <https://sass-lang.com/>`_ to css) - *optional - only for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install JavaScript modules using ``npm``:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `pip install -e .`
~> isso run
Install `sphinx <http://www.sphinx-doc.org/>`_ for generating docs:
.. code-block:: sh
~> pip install sphinx
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| ix5 | fb6f731f6bcbb871f5b3632843a09d2ed501a596 | 28beb7e848db5ce0e89f8a63e929ecaca4dcf529 | I agree that using `pip install -e .` is handy during development since you do not need to install the package again after every change. Since this part of the documentation is about installing from source I think both installation variants are fine and it depends on the use case which one to choose.
So all in all I'd say drop the final `Note: ` line, the rest is just fine. | stefangehn | 95 |
posativ/isso | 703 | docs: install: Reorder Install from source, py3.5 | Reorder steps so that js files are generated before `python setup.py develop`.
Clarify that isso should be installed in editable mode when installed from source.
Clarify that sphinx is needed for docs, and only for docs.
Clarify that npm is definitely required.
Isso requires python 3.5 now. | null | 2021-02-05 09:16:57+00:00 | 2021-12-24 01:58:20+00:00 | docs/docs/install.rst | Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 2.7 or 3.4+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *for frontend*
- `sassc <https://github.com/sass/sassc>`_ for compiling
`.scss <https://sass-lang.com/>`_ - *for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `install`
~> isso run
Install JavaScript modules:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| Installation
============
Isso is a web application written in Python. If pip and virtualenv mean anything
to you, continue with :ref:`install-from-pypi`. If you are running
Debian/Ubuntu, Gentoo, Archlinux or Fedora, you can use
:ref:`prebuilt-package`. If not, read the next section carefully.
.. contents::
:local:
:depth: 1
.. _install-interludium:
Interludium: Python is not PHP
------------------------------
If you think hosting a web application written in Python is as easy as one
written in PHP, you are wrong. Unlike for PHP, many Linux distribution use
Python for internal tools. Your package manager already ships several python
libraries, but most likely not all required by Isso (or in an up-to-date
version – looking at you, Debian!).
That's why most Python developers use the `Python Package Index`_ to get their
dependencies. The most important rule to follow is to never install *anything* from PyPi
as root. Not because of malicious software, but because you *will* break your
system.
``easy_install`` is one tool to mess up your system. Another package manager is
``pip``. If you ever searched for an issue with Python/pip and Stackoverflow is
suggesting you ``easy_install pip`` or ``pip install --upgrade pip`` (as root
of course!), you are doing it wrong. `Why you should not use Python's
easy_install carelessly on Debian`_ is worth the read.
Fortunately, Python has a way to install packages (both as root and as user)
without interfering with your globally installed packages: `virtualenv`. Use
this *always* if you are installing software unavailable in your favourite
package manager.
.. code-block:: sh
# for Debian/Ubuntu
~> sudo apt-get install python-setuptools python-virtualenv python-dev
# Fedora/Red Hat
~> sudo yum install python-setuptools python-virtualenv python-devel
The next steps should be done as regular user, not as root (although possible
but not recommended):
.. code-block:: sh
~> virtualenv /opt/isso
~> source /opt/isso/bin/activate
After calling `source`, you can now install packages from PyPi locally into this
virtual environment. If you don't like Isso anymore, you just `rm -rf` the
folder. Inside this virtual environment, you may also execute the example
commands from above to upgrade your Python Package Manager (although it barely
makes sense), it is completely independent from your global system.
To use Isso installed in a virtual environment outside of the virtual
environment, you just need to add */opt/isso/bin* to your :envvar:`PATH` or
execute */opt/isso/bin/isso* directly. It will launch Isso from within the
virtual environment.
With a virtualenv active, you may now continue to :ref:`install-from-pypi`!
Of course you may not need a virtualenv when you are running dedicated virtual
machines or a shared host (e.g. Uberspace.de).
.. _Python Package Index: https://pypi.python.org/pypi
.. _Why you should not use Python's easy_install carelessly on Debian:
https://workaround.org/easy-install-debian
.. _install-from-pypi:
Install from PyPi
-----------------
Requirements
^^^^^^^^^^^^
- Python 3.5+ (+ devel headers)
- SQLite 3.3.8 or later
- a working C compiler
For Debian/Ubuntu just `copy and paste
<http://thejh.net/misc/website-terminal-copy-paste>`_ to your terminal:
.. code-block:: sh
~> sudo apt-get install python-dev sqlite3 build-essential
Similar for Fedora (and derivates):
.. code-block:: sh
~> sudo yum install python-devel sqlite
~> sudo yum groupinstall “Development Tools”
Installation
^^^^^^^^^^^^
Install Isso with `pip <http://www.pip-installer.org/en/latest/>`_:
.. code-block:: sh
~> pip install isso
`Don't have pip? <https://twitter.com/gardaud/status/357638468572151808>`_
.. code-block:: sh
~> easy_install isso # cross your fingers
For easier execution, you can symlink the executable to a location in your
:envvar:`PATH`.
.. code-block:: sh
~> ln -s /opt/isso/bin/isso /usr/local/bin/isso
Upgrade
^^^^^^^
To upgrade Isso, activate your virtual environment again, and run
.. code-block:: sh
~> source /opt/isso/bin/activate # optional
~> pip install --upgrade isso
.. _prebuilt-package:
Prebuilt Packages
-----------------
* Debian (since Buster): https://packages.debian.org/search?keywords=isso
* Gentoo: http://eroen.eu/cgit/cgit.cgi/eroen-overlay/tree/www-apps/isso?h=isso
– not yet available in Portage, but you can use the ebuild to build Isso.
* Arch Linux: https://aur.archlinux.org/packages/isso/
– install with `yaourt isso`.
* Fedora: https://copr.fedoraproject.org/coprs/jujens/isso/ — copr
repository. Built from Pypi, includes a systemctl unit script.
Build a Docker image
--------------------
You can get a Docker image by running ``docker build . -t
isso``. Assuming you have your configuration in ``/opt/isso``, you can
use the following command to spawn the Docker container:
.. code-block:: sh
~> docker run -d --rm --name isso -p 127.0.0.1:8080:8080 -v /opt/isso:/config -v /opt/isso:/db isso
Then, you can use a reverse proxy to expose port 8080.
Install from Source
-------------------
If you want to hack on Isso or track down issues, there's an alternate
way to set up Isso. It requires a lot more dependencies and effort:
- Python 3.5+ (+ devel headers)
- Virtualenv
- SQLite 3.3.8 or later
- a working C compiler
- Node.js, `NPM <https://npmjs.org/>`__ - *required for frontend*
- `sphinx <http://www.sphinx-doc.org/>`_,
`sassc <https://github.com/sass/sassc>`_ (for compiling
`.scss <https://sass-lang.com/>`_ to css) - *optional - only for docs*
Get a fresh copy of Isso:
.. code-block:: sh
~> git clone https://github.com/posativ/isso.git
~> cd isso/
To create a virtual environment (recommended), run:
.. code-block:: sh
~> virtualenv .
~> source ./bin/activate
Install JavaScript modules using ``npm``:
.. code-block:: sh
~> make init
Build JavaScript frontend code:
.. code-block:: sh
~> make js
Install Isso and its dependencies:
.. code-block:: sh
~> python setup.py develop # or `pip install -e .`
~> isso run
Install `sphinx <http://www.sphinx-doc.org/>`_ for generating docs:
.. code-block:: sh
~> pip install sphinx
Generate docs:
.. code-block:: sh
~> make site
.. _init-scripts:
Init scripts
------------
Init scripts to run Isso as a service (check your distribution's documentation
for your init-system; e.g. Debian uses SysVinit, Fedora uses systemd) if you
don't use FastCGi or uWSGI:
- systemd (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.service
- SysVinit (Isso + Gunicorn): https://salsa.debian.org/jelmer/isso/-/blob/master/debian/isso.init
- OpenBSD: https://gist.github.com/noqqe/7397719
- FreeBSD: https://gist.github.com/ckoepp/52f6f0262de04cee1b88ef4a441e276d
- Supervisor: https://github.com/posativ/isso/issues/47
If you're writing your own init script, you can utilize ``start-stop-daemon``
to run Isso in the background (Isso runs in the foreground usually). Below you
will find a very basic SysVinit script which you can use for inspiration:
.. code-block:: sh
#!/bin/sh
### BEGIN INIT INFO
# Provides: isso
# Required-Start: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: lightweight Disqus alternative
### END INIT INFO
EXEC=/opt/isso/bin/isso
EXEC_OPTS="-c /etc/isso.cfg run"
RUNAS=isso
PIDFILE=/var/run/isso.pid
start() {
echo 'Starting service…' >&2
start-stop-daemon --start --user "$RUNAS" --background --make-pidfile --pidfile $PIDFILE \
--exec $EXEC -- $EXEC_OPTS
}
stop() {
echo 'Stopping service…' >&2
start-stop-daemon --stop --user "$RUNAS" --pidfile $PIDFILE --exec $EXEC
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
| ix5 | fb6f731f6bcbb871f5b3632843a09d2ed501a596 | 28beb7e848db5ce0e89f8a63e929ecaca4dcf529 | Line dropped | ix5 | 96 |
posativ/isso | 697 | Build JavaScript files during python package build | Make package builds via setuptools automatically trigger building of
merged & minified JS assets.
This fixes installing isso from source when using `pip install` as long
as both the python and node requirements are met. It also ensures that
`setup.py` commands like `build` or `bdist_wheel` create archives that
contain generated JS code. | null | 2021-02-03 18:30:50+00:00 | 2022-01-04 19:29:06+00:00 | setup.py | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from setuptools import setup, find_packages
requires = ['itsdangerous', 'Jinja2', 'misaka>=2.0,<3.0', 'html5lib',
'werkzeug>=1.0', 'bleach', 'Flask-Caching>=1.9', 'Flask']
setup(
name='isso',
version='0.12.5',
author='Martin Zimmermann',
author_email='info@posativ.org',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
url='https://github.com/posativ/isso/',
license='MIT',
description='lightweight Disqus alternative',
python_requires='>=3.5',
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9"
],
install_requires=requires,
entry_points={
'console_scripts':
['isso = isso:main'],
}
)
| #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import os
import setuptools.command.build_py
import subprocess
from setuptools import setup, find_packages
requires = ['itsdangerous', 'Jinja2', 'misaka>=2.0,<3.0', 'html5lib',
'werkzeug>=1.0', 'bleach', 'Flask-Caching>=1.9', 'Flask']
class NpmBuildCommand(setuptools.command.build_py.build_py):
"""Prefix Python build with node-based asset build"""
def run(self):
if 'TOX_ENV' not in os.environ:
subprocess.check_call(['make', 'init', 'js'])
setuptools.command.build_py.build_py.run(self)
setup(
name='isso',
version='0.12.5',
author='Martin Zimmermann',
author_email='info@posativ.org',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
url='https://github.com/posativ/isso/',
license='MIT',
description='lightweight Disqus alternative',
python_requires='>=3.5',
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9"
],
install_requires=requires,
entry_points={
'console_scripts':
['isso = isso:main'],
},
cmdclass={
'build_py': NpmBuildCommand,
},
)
| stefangehn | e6dbd21819f8fdca9fdace447e9ba01276e8d6a9 | bbad14e8e1384d49cd274f573cfe8ea121fef532 | check_call() ? | jelmer | 97 |
posativ/isso | 697 | Build JavaScript files during python package build | Make package builds via setuptools automatically trigger building of
merged & minified JS assets.
This fixes installing isso from source when using `pip install` as long
as both the python and node requirements are met. It also ensures that
`setup.py` commands like `build` or `bdist_wheel` create archives that
contain generated JS code. | null | 2021-02-03 18:30:50+00:00 | 2022-01-04 19:29:06+00:00 | setup.py | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from setuptools import setup, find_packages
requires = ['itsdangerous', 'Jinja2', 'misaka>=2.0,<3.0', 'html5lib',
'werkzeug>=1.0', 'bleach', 'Flask-Caching>=1.9', 'Flask']
setup(
name='isso',
version='0.12.5',
author='Martin Zimmermann',
author_email='info@posativ.org',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
url='https://github.com/posativ/isso/',
license='MIT',
description='lightweight Disqus alternative',
python_requires='>=3.5',
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9"
],
install_requires=requires,
entry_points={
'console_scripts':
['isso = isso:main'],
}
)
| #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import os
import setuptools.command.build_py
import subprocess
from setuptools import setup, find_packages
requires = ['itsdangerous', 'Jinja2', 'misaka>=2.0,<3.0', 'html5lib',
'werkzeug>=1.0', 'bleach', 'Flask-Caching>=1.9', 'Flask']
class NpmBuildCommand(setuptools.command.build_py.build_py):
"""Prefix Python build with node-based asset build"""
def run(self):
if 'TOX_ENV' not in os.environ:
subprocess.check_call(['make', 'init', 'js'])
setuptools.command.build_py.build_py.run(self)
setup(
name='isso',
version='0.12.5',
author='Martin Zimmermann',
author_email='info@posativ.org',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
url='https://github.com/posativ/isso/',
license='MIT',
description='lightweight Disqus alternative',
python_requires='>=3.5',
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Internet",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9"
],
install_requires=requires,
entry_points={
'console_scripts':
['isso = isso:main'],
},
cmdclass={
'build_py': NpmBuildCommand,
},
)
| stefangehn | e6dbd21819f8fdca9fdace447e9ba01276e8d6a9 | bbad14e8e1384d49cd274f573cfe8ea121fef532 | Indeed. Although `subprocess.run(..., check=True)` does the same I find `subprocess.check_call()` to be a bit more obvious and in fact know it from Python 2.7 already. | stefangehn | 98 |
posativ/isso | 686 | utils: html: Normalize misaka extensions | As of version 0.12.2, Isso uses misaka 2.0 to render markdown. Misaka 2.0 uses `dashed-case` instead of `snake_case` for options.
Normalize passed extensions to dashed-case to avoid mistakes.
Note: Flags have only been around in Isso with misaka 2.0, so I hope users did not use dashed case with them. | null | 2021-01-17 19:07:06+00:00 | 2022-01-05 20:17:38+00:00 | isso/utils/html.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import html
import bleach
import misaka
from configparser import NoOptionError
class Sanitizer(object):
def __init__(self, elements, attributes):
# attributes found in Sundown's HTML serializer [1]
# except for <img> tag,
# because images are not generated anyways.
#
# [1] https://github.com/vmg/sundown/blob/master/html/html.c
self.elements = ["a", "p", "hr", "br", "ol", "ul", "li",
"pre", "code", "blockquote",
"del", "ins", "strong", "em",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "th", "td"] + elements
# href for <a> and align for <table>
self.attributes = ["align", "href"] + attributes
def sanitize(self, text):
clean_html = bleach.clean(text, tags=self.elements, attributes=self.attributes, strip=True)
def set_links(attrs, new=False):
href_key = (None, u'href')
if href_key not in attrs:
return attrs
if attrs[href_key].startswith(u'mailto:'):
return attrs
rel_key = (None, u'rel')
rel_values = [val for val in attrs.get(rel_key, u'').split(u' ') if val]
for value in [u'nofollow', u'noopener']:
if value not in [rel_val.lower() for rel_val in rel_values]:
rel_values.append(value)
attrs[rel_key] = u' '.join(rel_values)
return attrs
linker = bleach.linkifier.Linker(callbacks=[set_links])
return linker.linkify(clean_html)
def Markdown(extensions=("strikethrough", "superscript", "autolink",
"fenced-code"), flags=[]):
renderer = Unofficial(flags=flags)
md = misaka.Markdown(renderer, extensions=extensions)
def inner(text):
rv = md(text).rstrip("\n")
if rv.startswith("<p>") or rv.endswith("</p>"):
return rv
return "<p>" + rv + "</p>"
return inner
class Unofficial(misaka.HtmlRenderer):
"""A few modifications to process "common" Markdown.
For instance, fenced code blocks (~~~ or ```) are just wrapped in <code>
which does not preserve line breaks. If a language is given, it is added
to <code class="$lang">, compatible with Highlight.js.
"""
def blockcode(self, text, lang):
lang = ' class="{0}"'.format(html.escape(lang)) if lang else ''
return "<pre><code{1}>{0}</code></pre>\n".format(html.escape(text, False), lang)
class Markup(object):
def __init__(self, conf):
try:
conf_flags = conf.getlist("flags")
except NoOptionError:
conf_flags = []
parser = Markdown(extensions=conf.getlist("options"), flags=conf_flags)
sanitizer = Sanitizer(
conf.getlist("allowed-elements"),
conf.getlist("allowed-attributes"))
self._render = lambda text: sanitizer.sanitize(parser(text))
def render(self, text):
return self._render(text)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import html
import bleach
import misaka
from configparser import NoOptionError
class Sanitizer(object):
def __init__(self, elements, attributes):
# attributes found in Sundown's HTML serializer [1]
# except for <img> tag,
# because images are not generated anyways.
#
# [1] https://github.com/vmg/sundown/blob/master/html/html.c
self.elements = ["a", "p", "hr", "br", "ol", "ul", "li",
"pre", "code", "blockquote",
"del", "ins", "strong", "em",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "th", "td"] + elements
# href for <a> and align for <table>
self.attributes = ["align", "href"] + attributes
def sanitize(self, text):
clean_html = bleach.clean(text, tags=self.elements, attributes=self.attributes, strip=True)
def set_links(attrs, new=False):
href_key = (None, u'href')
if href_key not in attrs:
return attrs
if attrs[href_key].startswith(u'mailto:'):
return attrs
rel_key = (None, u'rel')
rel_values = [val for val in attrs.get(rel_key, u'').split(u' ') if val]
for value in [u'nofollow', u'noopener']:
if value not in [rel_val.lower() for rel_val in rel_values]:
rel_values.append(value)
attrs[rel_key] = u' '.join(rel_values)
return attrs
linker = bleach.linkifier.Linker(callbacks=[set_links])
return linker.linkify(clean_html)
def Markdown(extensions=("strikethrough", "superscript", "autolink",
"fenced-code"), flags=[]):
# Normalize render extensions for misaka 2.0, which uses `dashed-case`
# instead of `snake_case` (misaka 1.x) for options.
extensions = [x.replace("_", "-") for x in extensions]
renderer = Unofficial(flags=flags)
md = misaka.Markdown(renderer, extensions=extensions)
def inner(text):
rv = md(text).rstrip("\n")
if rv.startswith("<p>") or rv.endswith("</p>"):
return rv
return "<p>" + rv + "</p>"
return inner
class Unofficial(misaka.HtmlRenderer):
"""A few modifications to process "common" Markdown.
For instance, fenced code blocks (~~~ or ```) are just wrapped in <code>
which does not preserve line breaks. If a language is given, it is added
to <code class="$lang">, compatible with Highlight.js.
"""
def blockcode(self, text, lang):
lang = ' class="{0}"'.format(html.escape(lang)) if lang else ''
return "<pre><code{1}>{0}</code></pre>\n".format(html.escape(text, False), lang)
class Markup(object):
def __init__(self, conf):
try:
conf_flags = conf.getlist("flags")
except NoOptionError:
conf_flags = []
parser = Markdown(extensions=conf.getlist("options"), flags=conf_flags)
sanitizer = Sanitizer(
conf.getlist("allowed-elements"),
conf.getlist("allowed-attributes"))
self._render = lambda text: sanitizer.sanitize(parser(text))
def render(self, text):
return self._render(text)
| ix5 | bbad14e8e1384d49cd274f573cfe8ea121fef532 | 86fbf37f3cf8c6c19b086976afa35ca65c092a29 | List comprehension would be prettier I guess? | ix5 | 99 |
posativ/isso | 686 | utils: html: Normalize misaka extensions | As of version 0.12.2, Isso uses misaka 2.0 to render markdown. Misaka 2.0 uses `dashed-case` instead of `snake_case` for options.
Normalize passed extensions to dashed-case to avoid mistakes.
Note: Flags have only been around in Isso with misaka 2.0, so I hope users did not use dashed case with them. | null | 2021-01-17 19:07:06+00:00 | 2022-01-05 20:17:38+00:00 | isso/utils/html.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import html
import bleach
import misaka
from configparser import NoOptionError
class Sanitizer(object):
def __init__(self, elements, attributes):
# attributes found in Sundown's HTML serializer [1]
# except for <img> tag,
# because images are not generated anyways.
#
# [1] https://github.com/vmg/sundown/blob/master/html/html.c
self.elements = ["a", "p", "hr", "br", "ol", "ul", "li",
"pre", "code", "blockquote",
"del", "ins", "strong", "em",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "th", "td"] + elements
# href for <a> and align for <table>
self.attributes = ["align", "href"] + attributes
def sanitize(self, text):
clean_html = bleach.clean(text, tags=self.elements, attributes=self.attributes, strip=True)
def set_links(attrs, new=False):
href_key = (None, u'href')
if href_key not in attrs:
return attrs
if attrs[href_key].startswith(u'mailto:'):
return attrs
rel_key = (None, u'rel')
rel_values = [val for val in attrs.get(rel_key, u'').split(u' ') if val]
for value in [u'nofollow', u'noopener']:
if value not in [rel_val.lower() for rel_val in rel_values]:
rel_values.append(value)
attrs[rel_key] = u' '.join(rel_values)
return attrs
linker = bleach.linkifier.Linker(callbacks=[set_links])
return linker.linkify(clean_html)
def Markdown(extensions=("strikethrough", "superscript", "autolink",
"fenced-code"), flags=[]):
renderer = Unofficial(flags=flags)
md = misaka.Markdown(renderer, extensions=extensions)
def inner(text):
rv = md(text).rstrip("\n")
if rv.startswith("<p>") or rv.endswith("</p>"):
return rv
return "<p>" + rv + "</p>"
return inner
class Unofficial(misaka.HtmlRenderer):
"""A few modifications to process "common" Markdown.
For instance, fenced code blocks (~~~ or ```) are just wrapped in <code>
which does not preserve line breaks. If a language is given, it is added
to <code class="$lang">, compatible with Highlight.js.
"""
def blockcode(self, text, lang):
lang = ' class="{0}"'.format(html.escape(lang)) if lang else ''
return "<pre><code{1}>{0}</code></pre>\n".format(html.escape(text, False), lang)
class Markup(object):
def __init__(self, conf):
try:
conf_flags = conf.getlist("flags")
except NoOptionError:
conf_flags = []
parser = Markdown(extensions=conf.getlist("options"), flags=conf_flags)
sanitizer = Sanitizer(
conf.getlist("allowed-elements"),
conf.getlist("allowed-attributes"))
self._render = lambda text: sanitizer.sanitize(parser(text))
def render(self, text):
return self._render(text)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import html
import bleach
import misaka
from configparser import NoOptionError
class Sanitizer(object):
def __init__(self, elements, attributes):
# attributes found in Sundown's HTML serializer [1]
# except for <img> tag,
# because images are not generated anyways.
#
# [1] https://github.com/vmg/sundown/blob/master/html/html.c
self.elements = ["a", "p", "hr", "br", "ol", "ul", "li",
"pre", "code", "blockquote",
"del", "ins", "strong", "em",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "th", "td"] + elements
# href for <a> and align for <table>
self.attributes = ["align", "href"] + attributes
def sanitize(self, text):
clean_html = bleach.clean(text, tags=self.elements, attributes=self.attributes, strip=True)
def set_links(attrs, new=False):
href_key = (None, u'href')
if href_key not in attrs:
return attrs
if attrs[href_key].startswith(u'mailto:'):
return attrs
rel_key = (None, u'rel')
rel_values = [val for val in attrs.get(rel_key, u'').split(u' ') if val]
for value in [u'nofollow', u'noopener']:
if value not in [rel_val.lower() for rel_val in rel_values]:
rel_values.append(value)
attrs[rel_key] = u' '.join(rel_values)
return attrs
linker = bleach.linkifier.Linker(callbacks=[set_links])
return linker.linkify(clean_html)
def Markdown(extensions=("strikethrough", "superscript", "autolink",
"fenced-code"), flags=[]):
# Normalize render extensions for misaka 2.0, which uses `dashed-case`
# instead of `snake_case` (misaka 1.x) for options.
extensions = [x.replace("_", "-") for x in extensions]
renderer = Unofficial(flags=flags)
md = misaka.Markdown(renderer, extensions=extensions)
def inner(text):
rv = md(text).rstrip("\n")
if rv.startswith("<p>") or rv.endswith("</p>"):
return rv
return "<p>" + rv + "</p>"
return inner
class Unofficial(misaka.HtmlRenderer):
"""A few modifications to process "common" Markdown.
For instance, fenced code blocks (~~~ or ```) are just wrapped in <code>
which does not preserve line breaks. If a language is given, it is added
to <code class="$lang">, compatible with Highlight.js.
"""
def blockcode(self, text, lang):
lang = ' class="{0}"'.format(html.escape(lang)) if lang else ''
return "<pre><code{1}>{0}</code></pre>\n".format(html.escape(text, False), lang)
class Markup(object):
def __init__(self, conf):
try:
conf_flags = conf.getlist("flags")
except NoOptionError:
conf_flags = []
parser = Markdown(extensions=conf.getlist("options"), flags=conf_flags)
sanitizer = Sanitizer(
conf.getlist("allowed-elements"),
conf.getlist("allowed-attributes"))
self._render = lambda text: sanitizer.sanitize(parser(text))
def render(self, text):
return self._render(text)
| ix5 | bbad14e8e1384d49cd274f573cfe8ea121fef532 | 86fbf37f3cf8c6c19b086976afa35ca65c092a29 | Yes, definitely:
```python
extensions = [x.replace("_", "-") for x in extensions]
``` | vincentbernat | 100 |
posativ/isso | 686 | utils: html: Normalize misaka extensions | As of version 0.12.2, Isso uses misaka 2.0 to render markdown. Misaka 2.0 uses `dashed-case` instead of `snake_case` for options.
Normalize passed extensions to dashed-case to avoid mistakes.
Note: Flags have only been around in Isso with misaka 2.0, so I hope users did not use dashed case with them. | null | 2021-01-17 19:07:06+00:00 | 2022-01-05 20:17:38+00:00 | isso/utils/html.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import html
import bleach
import misaka
from configparser import NoOptionError
class Sanitizer(object):
def __init__(self, elements, attributes):
# attributes found in Sundown's HTML serializer [1]
# except for <img> tag,
# because images are not generated anyways.
#
# [1] https://github.com/vmg/sundown/blob/master/html/html.c
self.elements = ["a", "p", "hr", "br", "ol", "ul", "li",
"pre", "code", "blockquote",
"del", "ins", "strong", "em",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "th", "td"] + elements
# href for <a> and align for <table>
self.attributes = ["align", "href"] + attributes
def sanitize(self, text):
clean_html = bleach.clean(text, tags=self.elements, attributes=self.attributes, strip=True)
def set_links(attrs, new=False):
href_key = (None, u'href')
if href_key not in attrs:
return attrs
if attrs[href_key].startswith(u'mailto:'):
return attrs
rel_key = (None, u'rel')
rel_values = [val for val in attrs.get(rel_key, u'').split(u' ') if val]
for value in [u'nofollow', u'noopener']:
if value not in [rel_val.lower() for rel_val in rel_values]:
rel_values.append(value)
attrs[rel_key] = u' '.join(rel_values)
return attrs
linker = bleach.linkifier.Linker(callbacks=[set_links])
return linker.linkify(clean_html)
def Markdown(extensions=("strikethrough", "superscript", "autolink",
"fenced-code"), flags=[]):
renderer = Unofficial(flags=flags)
md = misaka.Markdown(renderer, extensions=extensions)
def inner(text):
rv = md(text).rstrip("\n")
if rv.startswith("<p>") or rv.endswith("</p>"):
return rv
return "<p>" + rv + "</p>"
return inner
class Unofficial(misaka.HtmlRenderer):
"""A few modifications to process "common" Markdown.
For instance, fenced code blocks (~~~ or ```) are just wrapped in <code>
which does not preserve line breaks. If a language is given, it is added
to <code class="$lang">, compatible with Highlight.js.
"""
def blockcode(self, text, lang):
lang = ' class="{0}"'.format(html.escape(lang)) if lang else ''
return "<pre><code{1}>{0}</code></pre>\n".format(html.escape(text, False), lang)
class Markup(object):
def __init__(self, conf):
try:
conf_flags = conf.getlist("flags")
except NoOptionError:
conf_flags = []
parser = Markdown(extensions=conf.getlist("options"), flags=conf_flags)
sanitizer = Sanitizer(
conf.getlist("allowed-elements"),
conf.getlist("allowed-attributes"))
self._render = lambda text: sanitizer.sanitize(parser(text))
def render(self, text):
return self._render(text)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import html
import bleach
import misaka
from configparser import NoOptionError
class Sanitizer(object):
def __init__(self, elements, attributes):
# attributes found in Sundown's HTML serializer [1]
# except for <img> tag,
# because images are not generated anyways.
#
# [1] https://github.com/vmg/sundown/blob/master/html/html.c
self.elements = ["a", "p", "hr", "br", "ol", "ul", "li",
"pre", "code", "blockquote",
"del", "ins", "strong", "em",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "th", "td"] + elements
# href for <a> and align for <table>
self.attributes = ["align", "href"] + attributes
def sanitize(self, text):
clean_html = bleach.clean(text, tags=self.elements, attributes=self.attributes, strip=True)
def set_links(attrs, new=False):
href_key = (None, u'href')
if href_key not in attrs:
return attrs
if attrs[href_key].startswith(u'mailto:'):
return attrs
rel_key = (None, u'rel')
rel_values = [val for val in attrs.get(rel_key, u'').split(u' ') if val]
for value in [u'nofollow', u'noopener']:
if value not in [rel_val.lower() for rel_val in rel_values]:
rel_values.append(value)
attrs[rel_key] = u' '.join(rel_values)
return attrs
linker = bleach.linkifier.Linker(callbacks=[set_links])
return linker.linkify(clean_html)
def Markdown(extensions=("strikethrough", "superscript", "autolink",
"fenced-code"), flags=[]):
# Normalize render extensions for misaka 2.0, which uses `dashed-case`
# instead of `snake_case` (misaka 1.x) for options.
extensions = [x.replace("_", "-") for x in extensions]
renderer = Unofficial(flags=flags)
md = misaka.Markdown(renderer, extensions=extensions)
def inner(text):
rv = md(text).rstrip("\n")
if rv.startswith("<p>") or rv.endswith("</p>"):
return rv
return "<p>" + rv + "</p>"
return inner
class Unofficial(misaka.HtmlRenderer):
"""A few modifications to process "common" Markdown.
For instance, fenced code blocks (~~~ or ```) are just wrapped in <code>
which does not preserve line breaks. If a language is given, it is added
to <code class="$lang">, compatible with Highlight.js.
"""
def blockcode(self, text, lang):
lang = ' class="{0}"'.format(html.escape(lang)) if lang else ''
return "<pre><code{1}>{0}</code></pre>\n".format(html.escape(text, False), lang)
class Markup(object):
def __init__(self, conf):
try:
conf_flags = conf.getlist("flags")
except NoOptionError:
conf_flags = []
parser = Markdown(extensions=conf.getlist("options"), flags=conf_flags)
sanitizer = Sanitizer(
conf.getlist("allowed-elements"),
conf.getlist("allowed-attributes"))
self._render = lambda text: sanitizer.sanitize(parser(text))
def render(self, text):
return self._render(text)
| ix5 | bbad14e8e1384d49cd274f573cfe8ea121fef532 | 86fbf37f3cf8c6c19b086976afa35ca65c092a29 | Yup. | ix5 | 101 |
posativ/isso | 685 | share: isso.conf: Use dashed-case for misaka 2.0 | Misaka expects extensions and flags in `dashed-case` instead of the legacy `snake_case` as of version 2.0.
See https://github.com/FSX/misaka/blob/v2.1.1/misaka/utils.py#L15-L37
Also align "options" values with the defaults in `utils/html.py`. | null | 2021-01-17 19:01:05+00:00 | 2021-02-07 20:50:27+00:00 | share/isso.conf | # Isso configuration file
# vim: set filetype=ini
[general]
# file location to the SQLite3 database, highly recommended to change this
# location to a non-temporary location!
dbpath = /tmp/comments.db
# required to dispatch multiple websites, not used otherwise.
name =
# Your website(s). If Isso is unable to connect to at least one site, you'll
# get a warning during startup and comments are most likely non-functional.
#
# You'll need at least one host/website to run Isso. This is due to security
# reasons: Isso uses CORS_ to embed comments and to restrict comments only to
# your website, you have to "whitelist" your website(s).
#
# I recommend the first value to be a non-SSL website that is used as fallback
# if Firefox users (and only those) supress their HTTP referer completely:
#
# host =
# http://example.tld/
# https://example.tld/
#
host =
# time range that allows users to edit/remove their own comments.
# It supports years, weeks, days, hours, minutes, seconds.
# 3h45m12s equals to 3 hours, 45 minutes and 12 seconds.
max-age = 15m
# Select notification backend for new comments. Currently, only SMTP is
# available.
# Select notification backend(s) for new comments, separated by comma.
# Available backends:
#
# stdout
# Log to standard output. Default, if none selected.
# smtp
# Send notifications via SMTP on new comments with activation (if
# moderated) and deletion links.
notify = stdout
# Allow users to request E-mail notifications for replies to their post.
# WARNING: It is highly recommended to also turn on moderation when enabling
# this setting, as Isso can otherwise be easily exploited for sending spam.
reply-notifications=false
# Log console messages to file instead of standard output.
log-file =
# adds property "gravatar_image" to json response when true
# will automatically build md5 hash by email and use "gravatar_url" to build
# the url to the gravatar image
gravatar = false
# default url for gravatar. {} is where the hash will be placed
gravatar-url = https://www.gravatar.com/avatar/{}?d=identicon
# enable the "/latest" endpoint, that serves comment for multiple posts (not
# needing to previously know the posts URIs)
latest-enabled = false
[admin]
enabled = false
# Admin access password
password = please_choose_a_strong_password
[moderation]
# enable comment moderation queue. This option only affects new comments.
# Comments in modertion queue are not visible to other users until you activate
# them.
enabled = false
# with moderation enabled, automatically approve new comments by an
# author if they've had comments approved within the last 6 months
# Note: No verification is done on the email addresses entered by commenters.
# This means that if someone is able to guess correctly the email address used
# by a previously approved author, they will be able to have their new comment
# auto-approved. For this reason, we recommend that you also activate SMTP
# notification if you activate this option, so that you will see
# auto-approved comments as they get posted.
approve-if-email-previously-approved = false
# remove unprocessed comments in moderation queue after given time.
purge-after = 30d
[server]
# interface to listen on. Isso supports TCP/IP and unix domain sockets: UNIX
# domain socket listen = unix:///tmp/isso.sock TCP/IP listen =
# http:///localhost:1234/
#
# When gevent is available, it is automatically used for http:// Currently,
# gevent can not handle http requests on unix domain socket (see #295 and #299
# for details). Does not apply for uWSGI.
listen = http://localhost:8080
# public URL that Isso is accessed from by end users. Should always be a
# http:// or https:// absolute address. If left blank, automatic detection is
# attempted.
public-endpoint =
# reload application, when the source code has changed. Useful for development.
# Only works with the internal webserver.
reload = off
# show 10 most time consuming function in Isso after each request. Do not use
# in production.
profile = off
# an optional list of reverse proxies IPs behind which you have deployed
# your Isso web service (e.g. `127.0.0.1`).
# This allow for proper remote address resolution based on a
# `X-Forwarded-For` HTTP header, which is important for the mechanism
# forbiding several comment votes coming from the same subnet.
trusted-proxies =
[smtp]
# Isso can notify you on new comments via SMTP. In the email notification, you
# also can moderate (=activate or delete) comments.
# self-explanatory, optional
username =
# self-explanatory (yes, plain text, create a dedicated account for
# notifications), optional.
password =
# SMTP server
host = localhost
# SMTP port
port = 587
# use a secure connection to the server, possible values: none, starttls or
# ssl. Note, that there is no easy way for Python 2.7 and 3.3 to implement
# certification validation and thus the connection is vulnerable to
# Man-in-the-Middle attacks. You should definitely use a dedicated SMTP account
# for Isso in that case.
security = starttls
# recipient address, e.g. your email address
to =
# sender address, e.g. "Foo Bar" <isso@example.tld>
from =
# specify a timeout in seconds for blocking operations like the
# connection attempt.
timeout = 10
[guard]
# Enable basic spam protection features, e.g. rate-limit per IP address (/24
# for IPv4, /48 for IPv6).
# enable guard, recommended in production. Not useful for debugging purposes.
enabled = true
# limit to N new comments per minute.
ratelimit = 2
# how many comments directly to the thread (prevent a simple while true; do
# curl ...; done.
direct-reply = 3
# allow commenters to reply to their own comments when they could still edit
# the comment. After the editing timeframe is gone, commenters can reply to
# their own comments anyways. Do not forget to configure the client.
reply-to-self = false
# force commenters to enter a value into the author field. No validation is
# performed on the provided value. Do not forget to configure the client
# accordingly.
require-author = false
# require the commenter to enter an email address (note: no validation is
# done on the provided address). Do not forget to configure the client.
require-email = false
[markup]
# Customize markup and sanitized HTML. Currently, only Markdown (via Misaka) is
# supported, but new languages are relatively easy to add.
# Misaka-specific Markdown extensions, all flags starting with EXT_ can be used
# there, separated by comma.
options = strikethrough, autolink, fenced_code, no_intra_emphasis
# Misaka-specific HTML rendering flags, all html rendering flags can be used
# here, separated by comma, either by their name or as HTML_<flag>.
# Per Misaka's defaults, no flags are set.
flags =
# Additional HTML tags to allow in the generated output, comma-separated. By
# default, only a, blockquote, br, code, del, em, h1, h2, h3, h4, h5, h6, hr,
# ins, li, ol, p, pre, strong, table, tbody, td, th, thead and ul are allowed.
allowed-elements =
# Additional HTML attributes (independent from elements) to allow in the
# generated output, comma-separated. By default, only align and href are
# allowed.
allowed-attributes =
[hash]
# Customize used hash functions to hide the actual email addresses from
# commenters but still be able to generate an identicon.
# A salt is used to protect against rainbow tables. Isso does not make use of
# pepper (yet). The default value has been in use since the release of Isso and
# generates the same identicons for same addresses across installations.
salt = Eech7co8Ohloopo9Ol6baimi
# Hash algorithm to use -- either from Python's hashlib or PBKDF2 (a
# computational expensive hash function).
#
# The actual identifier for PBKDF2 is pbkdf2:1000:6:sha1, which means 1000
# iterations, 6 bytes to generate and SHA1 as pseudo-random family used for key
# strengthening. Arguments have to be in that order, but can be reduced to
# pbkdf2:4096 for example to override the iterations only.
algorithm = pbkdf2
[rss]
# Provide an Atom feed for each comment thread for users to subscribe to.
# The base URL of pages is needed to build the Atom feed. By appending
# the URI, we should get the complete URL to use to access the page
# with the comments. When empty, Atom feeds are disabled.
base =
# Limit the number of elements to return for each thread.
limit = 100
| # Isso configuration file
# vim: set filetype=ini
[general]
# file location to the SQLite3 database, highly recommended to change this
# location to a non-temporary location!
dbpath = /tmp/comments.db
# required to dispatch multiple websites, not used otherwise.
name =
# Your website(s). If Isso is unable to connect to at least one site, you'll
# get a warning during startup and comments are most likely non-functional.
#
# You'll need at least one host/website to run Isso. This is due to security
# reasons: Isso uses CORS_ to embed comments and to restrict comments only to
# your website, you have to "whitelist" your website(s).
#
# I recommend the first value to be a non-SSL website that is used as fallback
# if Firefox users (and only those) supress their HTTP referer completely:
#
# host =
# http://example.tld/
# https://example.tld/
#
host =
# time range that allows users to edit/remove their own comments.
# It supports years, weeks, days, hours, minutes, seconds.
# 3h45m12s equals to 3 hours, 45 minutes and 12 seconds.
max-age = 15m
# Select notification backend for new comments. Currently, only SMTP is
# available.
# Select notification backend(s) for new comments, separated by comma.
# Available backends:
#
# stdout
# Log to standard output. Default, if none selected.
# smtp
# Send notifications via SMTP on new comments with activation (if
# moderated) and deletion links.
notify = stdout
# Allow users to request E-mail notifications for replies to their post.
# WARNING: It is highly recommended to also turn on moderation when enabling
# this setting, as Isso can otherwise be easily exploited for sending spam.
reply-notifications=false
# Log console messages to file instead of standard output.
log-file =
# adds property "gravatar_image" to json response when true
# will automatically build md5 hash by email and use "gravatar_url" to build
# the url to the gravatar image
gravatar = false
# default url for gravatar. {} is where the hash will be placed
gravatar-url = https://www.gravatar.com/avatar/{}?d=identicon
# enable the "/latest" endpoint, that serves comment for multiple posts (not
# needing to previously know the posts URIs)
latest-enabled = false
[admin]
enabled = false
# Admin access password
password = please_choose_a_strong_password
[moderation]
# enable comment moderation queue. This option only affects new comments.
# Comments in modertion queue are not visible to other users until you activate
# them.
enabled = false
# with moderation enabled, automatically approve new comments by an
# author if they've had comments approved within the last 6 months
# Note: No verification is done on the email addresses entered by commenters.
# This means that if someone is able to guess correctly the email address used
# by a previously approved author, they will be able to have their new comment
# auto-approved. For this reason, we recommend that you also activate SMTP
# notification if you activate this option, so that you will see
# auto-approved comments as they get posted.
approve-if-email-previously-approved = false
# remove unprocessed comments in moderation queue after given time.
purge-after = 30d
[server]
# interface to listen on. Isso supports TCP/IP and unix domain sockets: UNIX
# domain socket listen = unix:///tmp/isso.sock TCP/IP listen =
# http:///localhost:1234/
#
# When gevent is available, it is automatically used for http:// Currently,
# gevent can not handle http requests on unix domain socket (see #295 and #299
# for details). Does not apply for uWSGI.
listen = http://localhost:8080
# public URL that Isso is accessed from by end users. Should always be a
# http:// or https:// absolute address. If left blank, automatic detection is
# attempted.
public-endpoint =
# reload application, when the source code has changed. Useful for development.
# Only works with the internal webserver.
reload = off
# show 10 most time consuming function in Isso after each request. Do not use
# in production.
profile = off
# an optional list of reverse proxies IPs behind which you have deployed
# your Isso web service (e.g. `127.0.0.1`).
# This allow for proper remote address resolution based on a
# `X-Forwarded-For` HTTP header, which is important for the mechanism
# forbiding several comment votes coming from the same subnet.
trusted-proxies =
[smtp]
# Isso can notify you on new comments via SMTP. In the email notification, you
# also can moderate (=activate or delete) comments.
# self-explanatory, optional
username =
# self-explanatory (yes, plain text, create a dedicated account for
# notifications), optional.
password =
# SMTP server
host = localhost
# SMTP port
port = 587
# use a secure connection to the server, possible values: none, starttls or
# ssl. Note, that there is no easy way for Python 2.7 and 3.3 to implement
# certification validation and thus the connection is vulnerable to
# Man-in-the-Middle attacks. You should definitely use a dedicated SMTP account
# for Isso in that case.
security = starttls
# recipient address, e.g. your email address
to =
# sender address, e.g. "Foo Bar" <isso@example.tld>
from =
# specify a timeout in seconds for blocking operations like the
# connection attempt.
timeout = 10
[guard]
# Enable basic spam protection features, e.g. rate-limit per IP address (/24
# for IPv4, /48 for IPv6).
# enable guard, recommended in production. Not useful for debugging purposes.
enabled = true
# limit to N new comments per minute.
ratelimit = 2
# how many comments directly to the thread (prevent a simple while true; do
# curl ...; done.
direct-reply = 3
# allow commenters to reply to their own comments when they could still edit
# the comment. After the editing timeframe is gone, commenters can reply to
# their own comments anyways. Do not forget to configure the client.
reply-to-self = false
# force commenters to enter a value into the author field. No validation is
# performed on the provided value. Do not forget to configure the client
# accordingly.
require-author = false
# require the commenter to enter an email address (note: no validation is
# done on the provided address). Do not forget to configure the client.
require-email = false
[markup]
# Customize markup and sanitized HTML. Currently, only Markdown (via Misaka) is
# supported, but new languages are relatively easy to add.
# Misaka-specific Markdown extensions, all extensions can be used here,
# separated by comma, either by their name or by EXT_<extension>.
# Careful: Misaka 1.0 used "snake_case", but 2.0 needs "dashed-case"!
options = strikethrough, superscript, autolink, fenced-code
# Misaka-specific HTML rendering flags, all html rendering flags can be used
# here, separated by comma, either by their name or as HTML_<flag>.
# Per Misaka's defaults, no flags are set.
flags =
# Additional HTML tags to allow in the generated output, comma-separated. By
# default, only a, blockquote, br, code, del, em, h1, h2, h3, h4, h5, h6, hr,
# ins, li, ol, p, pre, strong, table, tbody, td, th, thead and ul are allowed.
allowed-elements =
# Additional HTML attributes (independent from elements) to allow in the
# generated output, comma-separated. By default, only align and href are
# allowed.
allowed-attributes =
[hash]
# Customize used hash functions to hide the actual email addresses from
# commenters but still be able to generate an identicon.
# A salt is used to protect against rainbow tables. Isso does not make use of
# pepper (yet). The default value has been in use since the release of Isso and
# generates the same identicons for same addresses across installations.
salt = Eech7co8Ohloopo9Ol6baimi
# Hash algorithm to use -- either from Python's hashlib or PBKDF2 (a
# computational expensive hash function).
#
# The actual identifier for PBKDF2 is pbkdf2:1000:6:sha1, which means 1000
# iterations, 6 bytes to generate and SHA1 as pseudo-random family used for key
# strengthening. Arguments have to be in that order, but can be reduced to
# pbkdf2:4096 for example to override the iterations only.
algorithm = pbkdf2
[rss]
# Provide an Atom feed for each comment thread for users to subscribe to.
# The base URL of pages is needed to build the Atom feed. By appending
# the URI, we should get the complete URL to use to access the page
# with the comments. When empty, Atom feeds are disabled.
base =
# Limit the number of elements to return for each thread.
limit = 100
| ix5 | 08703d03ace7089f157fbdf5d560209c66d713e1 | 72e624bf6aeaeffa03a26f7d258561269ae54eec | We've been on misaka 2.0 since 1.5, do we really need to mention misaka 1.0? | jelmer | 102 |
posativ/isso | 685 | share: isso.conf: Use dashed-case for misaka 2.0 | Misaka expects extensions and flags in `dashed-case` instead of the legacy `snake_case` as of version 2.0.
See https://github.com/FSX/misaka/blob/v2.1.1/misaka/utils.py#L15-L37
Also align "options" values with the defaults in `utils/html.py`. | null | 2021-01-17 19:01:05+00:00 | 2021-02-07 20:50:27+00:00 | share/isso.conf | # Isso configuration file
# vim: set filetype=ini
[general]
# file location to the SQLite3 database, highly recommended to change this
# location to a non-temporary location!
dbpath = /tmp/comments.db
# required to dispatch multiple websites, not used otherwise.
name =
# Your website(s). If Isso is unable to connect to at least one site, you'll
# get a warning during startup and comments are most likely non-functional.
#
# You'll need at least one host/website to run Isso. This is due to security
# reasons: Isso uses CORS_ to embed comments and to restrict comments only to
# your website, you have to "whitelist" your website(s).
#
# I recommend the first value to be a non-SSL website that is used as fallback
# if Firefox users (and only those) supress their HTTP referer completely:
#
# host =
# http://example.tld/
# https://example.tld/
#
host =
# time range that allows users to edit/remove their own comments.
# It supports years, weeks, days, hours, minutes, seconds.
# 3h45m12s equals to 3 hours, 45 minutes and 12 seconds.
max-age = 15m
# Select notification backend for new comments. Currently, only SMTP is
# available.
# Select notification backend(s) for new comments, separated by comma.
# Available backends:
#
# stdout
# Log to standard output. Default, if none selected.
# smtp
# Send notifications via SMTP on new comments with activation (if
# moderated) and deletion links.
notify = stdout
# Allow users to request E-mail notifications for replies to their post.
# WARNING: It is highly recommended to also turn on moderation when enabling
# this setting, as Isso can otherwise be easily exploited for sending spam.
reply-notifications=false
# Log console messages to file instead of standard output.
log-file =
# adds property "gravatar_image" to json response when true
# will automatically build md5 hash by email and use "gravatar_url" to build
# the url to the gravatar image
gravatar = false
# default url for gravatar. {} is where the hash will be placed
gravatar-url = https://www.gravatar.com/avatar/{}?d=identicon
# enable the "/latest" endpoint, that serves comment for multiple posts (not
# needing to previously know the posts URIs)
latest-enabled = false
[admin]
enabled = false
# Admin access password
password = please_choose_a_strong_password
[moderation]
# enable comment moderation queue. This option only affects new comments.
# Comments in modertion queue are not visible to other users until you activate
# them.
enabled = false
# with moderation enabled, automatically approve new comments by an
# author if they've had comments approved within the last 6 months
# Note: No verification is done on the email addresses entered by commenters.
# This means that if someone is able to guess correctly the email address used
# by a previously approved author, they will be able to have their new comment
# auto-approved. For this reason, we recommend that you also activate SMTP
# notification if you activate this option, so that you will see
# auto-approved comments as they get posted.
approve-if-email-previously-approved = false
# remove unprocessed comments in moderation queue after given time.
purge-after = 30d
[server]
# interface to listen on. Isso supports TCP/IP and unix domain sockets: UNIX
# domain socket listen = unix:///tmp/isso.sock TCP/IP listen =
# http:///localhost:1234/
#
# When gevent is available, it is automatically used for http:// Currently,
# gevent can not handle http requests on unix domain socket (see #295 and #299
# for details). Does not apply for uWSGI.
listen = http://localhost:8080
# public URL that Isso is accessed from by end users. Should always be a
# http:// or https:// absolute address. If left blank, automatic detection is
# attempted.
public-endpoint =
# reload application, when the source code has changed. Useful for development.
# Only works with the internal webserver.
reload = off
# show 10 most time consuming function in Isso after each request. Do not use
# in production.
profile = off
# an optional list of reverse proxies IPs behind which you have deployed
# your Isso web service (e.g. `127.0.0.1`).
# This allow for proper remote address resolution based on a
# `X-Forwarded-For` HTTP header, which is important for the mechanism
# forbiding several comment votes coming from the same subnet.
trusted-proxies =
[smtp]
# Isso can notify you on new comments via SMTP. In the email notification, you
# also can moderate (=activate or delete) comments.
# self-explanatory, optional
username =
# self-explanatory (yes, plain text, create a dedicated account for
# notifications), optional.
password =
# SMTP server
host = localhost
# SMTP port
port = 587
# use a secure connection to the server, possible values: none, starttls or
# ssl. Note, that there is no easy way for Python 2.7 and 3.3 to implement
# certification validation and thus the connection is vulnerable to
# Man-in-the-Middle attacks. You should definitely use a dedicated SMTP account
# for Isso in that case.
security = starttls
# recipient address, e.g. your email address
to =
# sender address, e.g. "Foo Bar" <isso@example.tld>
from =
# specify a timeout in seconds for blocking operations like the
# connection attempt.
timeout = 10
[guard]
# Enable basic spam protection features, e.g. rate-limit per IP address (/24
# for IPv4, /48 for IPv6).
# enable guard, recommended in production. Not useful for debugging purposes.
enabled = true
# limit to N new comments per minute.
ratelimit = 2
# how many comments directly to the thread (prevent a simple while true; do
# curl ...; done.
direct-reply = 3
# allow commenters to reply to their own comments when they could still edit
# the comment. After the editing timeframe is gone, commenters can reply to
# their own comments anyways. Do not forget to configure the client.
reply-to-self = false
# force commenters to enter a value into the author field. No validation is
# performed on the provided value. Do not forget to configure the client
# accordingly.
require-author = false
# require the commenter to enter an email address (note: no validation is
# done on the provided address). Do not forget to configure the client.
require-email = false
[markup]
# Customize markup and sanitized HTML. Currently, only Markdown (via Misaka) is
# supported, but new languages are relatively easy to add.
# Misaka-specific Markdown extensions, all flags starting with EXT_ can be used
# there, separated by comma.
options = strikethrough, autolink, fenced_code, no_intra_emphasis
# Misaka-specific HTML rendering flags, all html rendering flags can be used
# here, separated by comma, either by their name or as HTML_<flag>.
# Per Misaka's defaults, no flags are set.
flags =
# Additional HTML tags to allow in the generated output, comma-separated. By
# default, only a, blockquote, br, code, del, em, h1, h2, h3, h4, h5, h6, hr,
# ins, li, ol, p, pre, strong, table, tbody, td, th, thead and ul are allowed.
allowed-elements =
# Additional HTML attributes (independent from elements) to allow in the
# generated output, comma-separated. By default, only align and href are
# allowed.
allowed-attributes =
[hash]
# Customize used hash functions to hide the actual email addresses from
# commenters but still be able to generate an identicon.
# A salt is used to protect against rainbow tables. Isso does not make use of
# pepper (yet). The default value has been in use since the release of Isso and
# generates the same identicons for same addresses across installations.
salt = Eech7co8Ohloopo9Ol6baimi
# Hash algorithm to use -- either from Python's hashlib or PBKDF2 (a
# computational expensive hash function).
#
# The actual identifier for PBKDF2 is pbkdf2:1000:6:sha1, which means 1000
# iterations, 6 bytes to generate and SHA1 as pseudo-random family used for key
# strengthening. Arguments have to be in that order, but can be reduced to
# pbkdf2:4096 for example to override the iterations only.
algorithm = pbkdf2
[rss]
# Provide an Atom feed for each comment thread for users to subscribe to.
# The base URL of pages is needed to build the Atom feed. By appending
# the URI, we should get the complete URL to use to access the page
# with the comments. When empty, Atom feeds are disabled.
base =
# Limit the number of elements to return for each thread.
limit = 100
| # Isso configuration file
# vim: set filetype=ini
[general]
# file location to the SQLite3 database, highly recommended to change this
# location to a non-temporary location!
dbpath = /tmp/comments.db
# required to dispatch multiple websites, not used otherwise.
name =
# Your website(s). If Isso is unable to connect to at least one site, you'll
# get a warning during startup and comments are most likely non-functional.
#
# You'll need at least one host/website to run Isso. This is due to security
# reasons: Isso uses CORS_ to embed comments and to restrict comments only to
# your website, you have to "whitelist" your website(s).
#
# I recommend the first value to be a non-SSL website that is used as fallback
# if Firefox users (and only those) supress their HTTP referer completely:
#
# host =
# http://example.tld/
# https://example.tld/
#
host =
# time range that allows users to edit/remove their own comments.
# It supports years, weeks, days, hours, minutes, seconds.
# 3h45m12s equals to 3 hours, 45 minutes and 12 seconds.
max-age = 15m
# Select notification backend for new comments. Currently, only SMTP is
# available.
# Select notification backend(s) for new comments, separated by comma.
# Available backends:
#
# stdout
# Log to standard output. Default, if none selected.
# smtp
# Send notifications via SMTP on new comments with activation (if
# moderated) and deletion links.
notify = stdout
# Allow users to request E-mail notifications for replies to their post.
# WARNING: It is highly recommended to also turn on moderation when enabling
# this setting, as Isso can otherwise be easily exploited for sending spam.
reply-notifications=false
# Log console messages to file instead of standard output.
log-file =
# adds property "gravatar_image" to json response when true
# will automatically build md5 hash by email and use "gravatar_url" to build
# the url to the gravatar image
gravatar = false
# default url for gravatar. {} is where the hash will be placed
gravatar-url = https://www.gravatar.com/avatar/{}?d=identicon
# enable the "/latest" endpoint, that serves comment for multiple posts (not
# needing to previously know the posts URIs)
latest-enabled = false
[admin]
enabled = false
# Admin access password
password = please_choose_a_strong_password
[moderation]
# enable comment moderation queue. This option only affects new comments.
# Comments in modertion queue are not visible to other users until you activate
# them.
enabled = false
# with moderation enabled, automatically approve new comments by an
# author if they've had comments approved within the last 6 months
# Note: No verification is done on the email addresses entered by commenters.
# This means that if someone is able to guess correctly the email address used
# by a previously approved author, they will be able to have their new comment
# auto-approved. For this reason, we recommend that you also activate SMTP
# notification if you activate this option, so that you will see
# auto-approved comments as they get posted.
approve-if-email-previously-approved = false
# remove unprocessed comments in moderation queue after given time.
purge-after = 30d
[server]
# interface to listen on. Isso supports TCP/IP and unix domain sockets: UNIX
# domain socket listen = unix:///tmp/isso.sock TCP/IP listen =
# http:///localhost:1234/
#
# When gevent is available, it is automatically used for http:// Currently,
# gevent can not handle http requests on unix domain socket (see #295 and #299
# for details). Does not apply for uWSGI.
listen = http://localhost:8080
# public URL that Isso is accessed from by end users. Should always be a
# http:// or https:// absolute address. If left blank, automatic detection is
# attempted.
public-endpoint =
# reload application, when the source code has changed. Useful for development.
# Only works with the internal webserver.
reload = off
# show 10 most time consuming function in Isso after each request. Do not use
# in production.
profile = off
# an optional list of reverse proxies IPs behind which you have deployed
# your Isso web service (e.g. `127.0.0.1`).
# This allow for proper remote address resolution based on a
# `X-Forwarded-For` HTTP header, which is important for the mechanism
# forbiding several comment votes coming from the same subnet.
trusted-proxies =
[smtp]
# Isso can notify you on new comments via SMTP. In the email notification, you
# also can moderate (=activate or delete) comments.
# self-explanatory, optional
username =
# self-explanatory (yes, plain text, create a dedicated account for
# notifications), optional.
password =
# SMTP server
host = localhost
# SMTP port
port = 587
# use a secure connection to the server, possible values: none, starttls or
# ssl. Note, that there is no easy way for Python 2.7 and 3.3 to implement
# certification validation and thus the connection is vulnerable to
# Man-in-the-Middle attacks. You should definitely use a dedicated SMTP account
# for Isso in that case.
security = starttls
# recipient address, e.g. your email address
to =
# sender address, e.g. "Foo Bar" <isso@example.tld>
from =
# specify a timeout in seconds for blocking operations like the
# connection attempt.
timeout = 10
[guard]
# Enable basic spam protection features, e.g. rate-limit per IP address (/24
# for IPv4, /48 for IPv6).
# enable guard, recommended in production. Not useful for debugging purposes.
enabled = true
# limit to N new comments per minute.
ratelimit = 2
# how many comments directly to the thread (prevent a simple while true; do
# curl ...; done.
direct-reply = 3
# allow commenters to reply to their own comments when they could still edit
# the comment. After the editing timeframe is gone, commenters can reply to
# their own comments anyways. Do not forget to configure the client.
reply-to-self = false
# force commenters to enter a value into the author field. No validation is
# performed on the provided value. Do not forget to configure the client
# accordingly.
require-author = false
# require the commenter to enter an email address (note: no validation is
# done on the provided address). Do not forget to configure the client.
require-email = false
[markup]
# Customize markup and sanitized HTML. Currently, only Markdown (via Misaka) is
# supported, but new languages are relatively easy to add.
# Misaka-specific Markdown extensions, all extensions can be used here,
# separated by comma, either by their name or by EXT_<extension>.
# Careful: Misaka 1.0 used "snake_case", but 2.0 needs "dashed-case"!
options = strikethrough, superscript, autolink, fenced-code
# Misaka-specific HTML rendering flags, all html rendering flags can be used
# here, separated by comma, either by their name or as HTML_<flag>.
# Per Misaka's defaults, no flags are set.
flags =
# Additional HTML tags to allow in the generated output, comma-separated. By
# default, only a, blockquote, br, code, del, em, h1, h2, h3, h4, h5, h6, hr,
# ins, li, ol, p, pre, strong, table, tbody, td, th, thead and ul are allowed.
allowed-elements =
# Additional HTML attributes (independent from elements) to allow in the
# generated output, comma-separated. By default, only align and href are
# allowed.
allowed-attributes =
[hash]
# Customize used hash functions to hide the actual email addresses from
# commenters but still be able to generate an identicon.
# A salt is used to protect against rainbow tables. Isso does not make use of
# pepper (yet). The default value has been in use since the release of Isso and
# generates the same identicons for same addresses across installations.
salt = Eech7co8Ohloopo9Ol6baimi
# Hash algorithm to use -- either from Python's hashlib or PBKDF2 (a
# computational expensive hash function).
#
# The actual identifier for PBKDF2 is pbkdf2:1000:6:sha1, which means 1000
# iterations, 6 bytes to generate and SHA1 as pseudo-random family used for key
# strengthening. Arguments have to be in that order, but can be reduced to
# pbkdf2:4096 for example to override the iterations only.
algorithm = pbkdf2
[rss]
# Provide an Atom feed for each comment thread for users to subscribe to.
# The base URL of pages is needed to build the Atom feed. By appending
# the URI, we should get the complete URL to use to access the page
# with the comments. When empty, Atom feeds are disabled.
base =
# Limit the number of elements to return for each thread.
limit = 100
| ix5 | 08703d03ace7089f157fbdf5d560209c66d713e1 | 72e624bf6aeaeffa03a26f7d258561269ae54eec | I was directing that comment towards people upgrading from older versions. | ix5 | 103 |
posativ/isso | 683 | Require an edit cookie to be able to view a comment to be edited. | The `/id` GET endpoint is only used to retrieve the raw text of a comment to be edited. Being able to arbitrarily retrieve *any* comment through this endpoint is a potential privacy issue, since it allows a malicious actor to individually retrieve all comments from a website without knowledge of an existing thread URI.
This change requires that comment text retrieval has a valid edit cookie.
Fixes #679 | null | 2021-01-15 22:32:12+00:00 | 2021-12-22 20:37:30+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4'
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fluffy-critter | 57aa12699a1338820c9ec34ebbae01d687d69c9f | 5f3bf4fb8e481e09259e8fdf53995fca3461ad59 | Maybe change the `apiExample` to
`curl 'https://comments.example.com/id/4' --cokie '4=<cookie>'` | ix5 | 104 |
posativ/isso | 683 | Require an edit cookie to be able to view a comment to be edited. | The `/id` GET endpoint is only used to retrieve the raw text of a comment to be edited. Being able to arbitrarily retrieve *any* comment through this endpoint is a potential privacy issue, since it allows a malicious actor to individually retrieve all comments from a website without knowledge of an existing thread URI.
This change requires that comment text retrieval has a valid edit cookie.
Fixes #679 | null | 2021-01-15 22:32:12+00:00 | 2021-12-22 20:37:30+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4'
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fluffy-critter | 57aa12699a1338820c9ec34ebbae01d687d69c9f | 5f3bf4fb8e481e09259e8fdf53995fca3461ad59 | Begone! | ix5 | 105 |
posativ/isso | 683 | Require an edit cookie to be able to view a comment to be edited. | The `/id` GET endpoint is only used to retrieve the raw text of a comment to be edited. Being able to arbitrarily retrieve *any* comment through this endpoint is a potential privacy issue, since it allows a malicious actor to individually retrieve all comments from a website without knowledge of an existing thread URI.
This change requires that comment text retrieval has a valid edit cookie.
Fixes #679 | null | 2021-01-15 22:32:12+00:00 | 2021-12-22 20:37:30+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4'
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fluffy-critter | 57aa12699a1338820c9ec34ebbae01d687d69c9f | 5f3bf4fb8e481e09259e8fdf53995fca3461ad59 | There's quite a few functions with that inconsistent spacing. Also *technically* the docstrings should be inside the functions, not outside of them. Fixing that feels a bit out-of-scope for this change. Maybe in the future there should be a docstring normalization pass. | fluffy-critter | 106 |
posativ/isso | 683 | Require an edit cookie to be able to view a comment to be edited. | The `/id` GET endpoint is only used to retrieve the raw text of a comment to be edited. Being able to arbitrarily retrieve *any* comment through this endpoint is a potential privacy issue, since it allows a malicious actor to individually retrieve all comments from a website without knowledge of an existing thread URI.
This change requires that comment text retrieval has a valid edit cookie.
Fixes #679 | null | 2021-01-15 22:32:12+00:00 | 2021-12-22 20:37:30+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4'
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fluffy-critter | 57aa12699a1338820c9ec34ebbae01d687d69c9f | 5f3bf4fb8e481e09259e8fdf53995fca3461ad59 | (That said, I'll remove that accidentally-introduced newline. No idea how that got in there!) | fluffy-critter | 107 |
posativ/isso | 683 | Require an edit cookie to be able to view a comment to be edited. | The `/id` GET endpoint is only used to retrieve the raw text of a comment to be edited. Being able to arbitrarily retrieve *any* comment through this endpoint is a potential privacy issue, since it allows a malicious actor to individually retrieve all comments from a website without knowledge of an existing thread URI.
This change requires that comment text retrieval has a valid edit cookie.
Fixes #679 | null | 2021-01-15 22:32:12+00:00 | 2021-12-22 20:37:30+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4'
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fluffy-critter | 57aa12699a1338820c9ec34ebbae01d687d69c9f | 5f3bf4fb8e481e09259e8fdf53995fca3461ad59 | Used `-b cookie.txt` to keep it in line with the other `@apiExample` annotations | fluffy-critter | 108 |
posativ/isso | 683 | Require an edit cookie to be able to view a comment to be edited. | The `/id` GET endpoint is only used to retrieve the raw text of a comment to be edited. Being able to arbitrarily retrieve *any* comment through this endpoint is a potential privacy issue, since it allows a malicious actor to individually retrieve all comments from a website without knowledge of an existing thread URI.
This change requires that comment text retrieval has a valid edit cookie.
Fixes #679 | null | 2021-01-15 22:32:12+00:00 | 2021-12-22 20:37:30+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4'
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fluffy-critter | 57aa12699a1338820c9ec34ebbae01d687d69c9f | 5f3bf4fb8e481e09259e8fdf53995fca3461ad59 | Yeah - I think there's value in fixing some of the formatting, but mixing those changes in with other changes just makes everything harder to review. | jelmer | 109 |
posativ/isso | 683 | Require an edit cookie to be able to view a comment to be edited. | The `/id` GET endpoint is only used to retrieve the raw text of a comment to be edited. Being able to arbitrarily retrieve *any* comment through this endpoint is a potential privacy issue, since it allows a malicious actor to individually retrieve all comments from a website without knowledge of an existing thread URI.
This change requires that comment text retrieval has a valid edit cookie.
Fixes #679 | null | 2021-01-15 22:32:12+00:00 | 2021-12-22 20:37:30+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4'
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fluffy-critter | 57aa12699a1338820c9ec34ebbae01d687d69c9f | 5f3bf4fb8e481e09259e8fdf53995fca3461ad59 | A thing I’ve found to be helpful is to make autopep8 part of the build process so that there’s never an opportunity for things to drift in the first place. | fluffy-critter | 110 |
posativ/isso | 683 | Require an edit cookie to be able to view a comment to be edited. | The `/id` GET endpoint is only used to retrieve the raw text of a comment to be edited. Being able to arbitrarily retrieve *any* comment through this endpoint is a potential privacy issue, since it allows a malicious actor to individually retrieve all comments from a website without knowledge of an existing thread URI.
This change requires that comment text retrieval has a valid edit cookie.
Fixes #679 | null | 2021-01-15 22:32:12+00:00 | 2021-12-22 20:37:30+00:00 | isso/views/comments.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4'
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from configparser import NoOptionError
import collections
import re
import time
import functools
import json # json.dumps to put URL in <script>
from datetime import datetime, timedelta
from itsdangerous import SignatureExpired, BadSignature
from xml.etree import ElementTree as ET
from werkzeug.http import dump_cookie
from werkzeug.wsgi import get_current_url
from werkzeug.utils import redirect
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from isso import utils, local
from isso.utils import (http, parse,
JSONResponse as JSON, XMLResponse as XML,
render_template)
from isso.views import requires
from isso.utils.hash import sha1
from isso.utils.hash import md5
try:
from cgi import escape
except ImportError:
from html import escape
from urllib.parse import urlparse
from urllib.parse import unquote
from io import BytesIO as StringIO
# from Django appearently, looks good to me *duck*
__url_re = re.compile(
r'^'
r'(https?://)?'
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)'
r'$', re.IGNORECASE)
def isurl(text):
return __url_re.match(text) is not None
def normalize(url):
if not url.startswith(("http://", "https://")):
return "http://" + url
return url
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
If the header is not sent or requests `application/json`, the request is
not forged (XHR is restricted by CORS separately).
"""
"""
@apiDefine csrf
@apiHeader {string="application/json"} Content-Type
The content type must be set to `application/json` to prevent CSRF attacks.
"""
def dec(self, env, req, *args, **kwargs):
if req.content_type and not req.content_type.startswith("application/json"):
raise Forbidden("CSRF")
return func(self, env, req, *args, **kwargs)
return dec
class API(object):
FIELDS = set(['id', 'parent', 'text', 'author', 'website',
'mode', 'created', 'modified', 'likes', 'dislikes', 'hash', 'gravatar_image', 'notification'])
# comment fields, that can be submitted
ACCEPT = set(['text', 'author', 'website', 'email', 'parent', 'title', 'notification'])
VIEWS = [
('fetch', ('GET', '/')),
('new', ('POST', '/new')),
('count', ('GET', '/count')),
('counts', ('POST', '/count')),
('feed', ('GET', '/feed')),
('latest', ('GET', '/latest')),
('view', ('GET', '/id/<int:id>')),
('edit', ('PUT', '/id/<int:id>')),
('delete', ('DELETE', '/id/<int:id>')),
('unsubscribe', ('GET', '/id/<int:id>/unsubscribe/<string:email>/<string:key>')),
('moderate', ('GET', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('moderate', ('POST', '/id/<int:id>/<any(edit,activate,delete):action>/<string:key>')),
('like', ('POST', '/id/<int:id>/like')),
('dislike', ('POST', '/id/<int:id>/dislike')),
('demo', ('GET', '/demo')),
('preview', ('POST', '/preview')),
('login', ('POST', '/login')),
('admin', ('GET', '/admin'))
]
def __init__(self, isso, hasher):
self.isso = isso
self.hash = hasher.uhash
self.cache = isso.cache
self.signal = isso.signal
self.conf = isso.conf.section("general")
self.moderated = isso.conf.getboolean("moderation", "enabled")
# this is similar to the wordpress setting "Comment author must have a previously approved comment"
try:
self.approve_if_email_previously_approved = isso.conf.getboolean("moderation", "approve-if-email-previously-approved")
except NoOptionError:
self.approve_if_email_previously_approved = False
try:
self.trusted_proxies = list(isso.conf.getiter("server", "trusted-proxies"))
except NoOptionError:
self.trusted_proxies = []
self.guard = isso.db.guard
self.threads = isso.db.threads
self.comments = isso.db.comments
for (view, (method, path)) in self.VIEWS:
isso.urls.add(
Rule(path, methods=[method], endpoint=getattr(self, view)))
@classmethod
def verify(cls, comment):
if "text" not in comment:
return False, "text is missing"
if not isinstance(comment.get("parent"), (int, type(None))):
return False, "parent must be an integer or null"
for key in ("text", "author", "website", "email"):
if not isinstance(comment.get(key), (str, type(None))):
return False, "%s must be a string or null" % key
if len(comment["text"].rstrip()) < 3:
return False, "text is too short (minimum length: 3)"
if len(comment["text"]) > 65535:
return False, "text is too long (maximum length: 65535)"
if len(comment.get("email") or "") > 254:
return False, "http://tools.ietf.org/html/rfc5321#section-4.5.3"
if comment.get("website"):
if len(comment["website"]) > 254:
return False, "arbitrary length limit"
if not isurl(comment["website"]):
return False, "Website not Django-conform"
return True, ""
# Common definitions for apidoc follow:
"""
@apiDefine plainParam
@apiParam {number=0,1} [plain]
Iff set to `1`, the plain text entered by the user will be returned in the comments’ `text` attribute (instead of the rendered markdown).
"""
"""
@apiDefine commentResponse
@apiSuccess {number} id
The comment’s id (assigned by the server).
@apiSuccess {number} parent
Id of the comment this comment is a reply to. `null` if this is a top-level-comment.
@apiSuccess {number=1,2,4} mode
The comment’s mode:
value | explanation
--- | ---
`1` | accepted: The comment was accepted by the server and is published.
`2` | in moderation queue: The comment was accepted by the server but awaits moderation.
`4` | deleted, but referenced: The comment was deleted on the server but is still referenced by replies.
@apiSuccess {string} author
The comments’s author’s name or `null`.
@apiSuccess {string} website
The comment’s author’s website or `null`.
@apiSuccess {string} hash
A hash uniquely identifying the comment’s author.
@apiSuccess {number} created
UNIX timestamp of the time the comment was created (on the server).
@apiSuccess {number} modified
UNIX timestamp of the time the comment was last modified (on the server). `null` if the comment was not yet modified.
"""
"""
@api {post} /new create new
@apiGroup Comment
@apiDescription
Creates a new comment. The response will set a cookie on the requestor to enable them to later edit the comment.
@apiUse csrf
@apiParam {string} uri
The uri of the thread to create the comment on.
@apiParam {string} text
The comment’s raw text.
@apiParam {string} [author]
The comment’s author’s name.
@apiParam {string} [email]
The comment’s author’s email address.
@apiParam {string} [website]
The comment’s author’s website’s url.
@apiParam {number} [parent]
The parent comment’s id iff the new comment is a response to an existing comment.
@apiExample {curl} Create a reply to comment with id 15:
curl 'https://comments.example.com/new?uri=/thread/' -d '{"text": "Stop saying that! *isso*!", "author": "Max Rant", "email": "rant@example.com", "parent": 15}' -H 'Content-Type: application/json' -c cookie.txt
@apiUse commentResponse
@apiSuccessExample Success after the above request:
{
"website": null,
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>Stop saying that! <em>isso</em>!</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "e644f6ee43c0",
"id": 23,
"likes": 0
}
"""
@xhr
@requires(str, 'uri')
def new(self, environ, request, uri):
data = request.get_json()
for field in set(data.keys()) - API.ACCEPT:
data.pop(field)
for key in ("author", "email", "website", "parent"):
data.setdefault(key, None)
valid, reason = API.verify(data)
if not valid:
return BadRequest(reason)
for field in ("author", "email", "website"):
if data.get(field) is not None:
data[field] = escape(data[field], quote=False)
if data.get("website"):
data["website"] = normalize(data["website"])
data['mode'] = 2 if self.moderated else 1
data['remote_addr'] = self._remote_addr(request)
with self.isso.lock:
if uri not in self.threads:
if 'title' not in data:
with http.curl('GET', local("origin"), uri) as resp:
if resp and resp.status == 200:
uri, title = parse.thread(resp.read(), id=uri)
else:
return NotFound('URI does not exist %s')
else:
title = data['title']
thread = self.threads.new(uri, title)
self.signal("comments.new:new-thread", thread)
else:
thread = self.threads[uri]
# notify extensions that the new comment is about to save
self.signal("comments.new:before-save", thread, data)
valid, reason = self.guard.validate(uri, data)
if not valid:
self.signal("comments.new:guard", reason)
raise Forbidden(reason)
with self.isso.lock:
# if email-based auto-moderation enabled, check for previously approved author
# right before approval.
if self.approve_if_email_previously_approved and self.comments.is_previously_approved_author(data['email']):
data['mode'] = 1
rv = self.comments.add(uri, data)
# notify extension, that the new comment has been successfully saved
self.signal("comments.new:after-save", thread, rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
rv["hash"] = self.hash(rv['email'] or rv['remote_addr'])
self.cache.set(
'hash', (rv['email'] or rv['remote_addr']).encode('utf-8'), rv['hash'])
rv = self._add_gravatar_image(rv)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
# success!
self.signal("comments.new:finish", thread, rv)
resp = JSON(rv, 202 if rv["mode"] == 2 else 201)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
def _remote_addr(self, request):
"""Return the anonymized IP address of the requester.
Takes into consideration a potential X-Forwarded-For HTTP header
if a necessary server.trusted-proxies configuration entry is set.
Recipe source: https://stackoverflow.com/a/22936947/636849
"""
remote_addr = request.remote_addr
if self.trusted_proxies:
route = request.access_route + [remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in self.trusted_proxies), remote_addr)
return utils.anonymize(str(remote_addr))
def create_cookie(self, **kwargs):
"""
Setting cookies to SameSite=None requires "Secure" attribute.
For http-only, we need to override the dump_cookie() default SameSite=None
or the cookie will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure
"""
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
samesite = self.isso.conf.get("server", "samesite")
if isso_host_script.startswith("https://"):
secure = True
samesite = samesite or "None"
else:
secure = False
samesite = samesite or "Lax"
return functools.partial(dump_cookie, **kwargs,
secure=secure, samesite=samesite)
"""
@api {get} /id/:id view
@apiGroup Comment
@apiDescription
View an existing comment, for the purpose of editing. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
The id of the comment to view.
@apiUse plainParam
@apiExample {curl} View the comment with id 4:
curl 'https://comments.example.com/id/4' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example result:
{
"website": null,
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 1
}
"""
def view(self, environ, request, id):
rv = self.comments.get(id)
if rv is None:
raise NotFound
try:
self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
if request.args.get('plain', '0') == '0':
rv['text'] = self.isso.render(rv['text'])
return JSON(rv, 200)
"""
@api {put} /id/:id edit
@apiGroup Comment
@apiDescription
Edit an existing comment. Editing a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details. Editing a comment will set a new edit cookie in the response.
@apiUse csrf
@apiParam {number} id
The id of the comment to edit.
@apiParam {string} text
A new (raw) text for the comment.
@apiParam {string} [author]
The modified comment’s author’s name.
@apiParam {string} [webiste]
The modified comment’s author’s website.
@apiExample {curl} Edit comment with id 23:
curl -X PUT 'https://comments.example.com/id/23' -d {"text": "I see your point. However, I still disagree.", "website": "maxrant.important.com"} -H 'Content-Type: application/json' -b cookie.txt
@apiUse commentResponse
@apiSuccessExample Example response:
{
"website": "maxrant.important.com",
"author": "Max Rant",
"parent": 15,
"created": 1464940838.254393,
"text": "<p>I see your point. However, I still disagree.</p>",
"dislikes": 0,
"modified": 1464943439.073961,
"mode": 1,
"id": 23,
"likes": 0
}
"""
@xhr
def edit(self, environ, request, id):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ''))
except (SignatureExpired, BadSignature):
raise Forbidden
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
data = request.get_json()
if "text" not in data or data["text"] is None or len(data["text"]) < 3:
raise BadRequest("no text given")
for key in set(data.keys()) - set(["text", "author", "website"]):
data.pop(key)
data['modified'] = time.time()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
cookie = self.create_cookie(
value=self.isso.sign([rv["id"], sha1(rv["text"])]),
max_age=self.conf.getint('max-age'))
rv["text"] = self.isso.render(rv["text"])
resp = JSON(rv, 200)
resp.headers.add("Set-Cookie", cookie(str(rv["id"])))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % rv["id"]))
return resp
"""
@api {delete} '/id/:id' delete
@apiGroup Comment
@apiDescription
Delete an existing comment. Deleting a comment is only possible for a short period of time after it was created and only if the requestor has a valid cookie for it. See the [isso server documentation](https://posativ.org/isso/docs/configuration/server) for details.
@apiParam {number} id
Id of the comment to delete.
@apiExample {curl} Delete comment with id 14:
curl -X DELETE 'https://comments.example.com/id/14' -b cookie.txt
@apiSuccessExample Successful deletion returns null:
null
"""
@xhr
def delete(self, environ, request, id, key=None):
try:
rv = self.isso.unsign(request.cookies.get(str(id), ""))
except (SignatureExpired, BadSignature):
raise Forbidden
else:
if rv[0] != id:
raise Forbidden
# verify checksum, mallory might skip cookie deletion when he deletes a comment
if rv[1] != sha1(self.comments.get(id)["text"]):
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
with self.isso.lock:
rv = self.comments.delete(id)
if rv:
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.delete", id)
resp = JSON(rv, 200)
cookie = self.create_cookie(expires=0, max_age=0)
resp.headers.add("Set-Cookie", cookie(str(id)))
resp.headers.add("X-Set-Cookie", cookie("isso-%i" % id))
return resp
"""
@api {get} /id/:id/:email/key unsubscribe
@apiGroup Comment
@apiDescription
Opt out from getting any further email notifications about replies to a particular comment. In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
@apiParam {number} id
The id of the comment to unsubscribe from replies to.
@apiParam {string} email
The email address of the subscriber.
@apiParam {string} key
The key to authenticate the subscriber.
@apiExample {curl} Unsubscribe Alice from replies to comment with id 13:
curl -X GET 'https://comments.example.com/id/13/unsubscribe/alice@example.com/WyJ1bnN1YnNjcmliZSIsImFsaWNlQGV4YW1wbGUuY29tIl0.DdcH9w.Wxou-l22ySLFkKUs7RUHnoM8Kos'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def unsubscribe(self, environ, request, id, email, key):
email = unquote(email)
try:
rv = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
if rv[0] != 'unsubscribe' or rv[1] != email:
raise Forbidden
item = self.comments.get(id)
if item is None:
raise NotFound
with self.isso.lock:
self.comments.unsubscribe(email, id)
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Successfully unsubscribed</title>"
"</head>"
"<body>"
" <p>You have been unsubscribed from replies in the given conversation.</p>"
"</body>"
"</html>")
return Response(modal, 200, content_type="text/html")
"""
@api {post} /id/:id/:action/key moderate
@apiGroup Comment
@apiDescription
Publish or delete a comment that is in the moderation queue (mode `2`). In order to use this endpoint, the requestor needs a `key` that is usually obtained from an email sent out by isso.
This endpoint can also be used with a `GET` request. In that case, a html page is returned that asks the user whether they are sure to perform the selected action. If they select “yes”, the query is repeated using `POST`.
@apiParam {number} id
The id of the comment to moderate.
@apiParam {string=activate,delete} action
`activate` to publish the comment (change its mode to `1`).
`delete` to delete the comment
@apiParam {string} key
The moderation key to authenticate the moderation.
@apiExample {curl} delete comment with id 13:
curl -X POST 'https://comments.example.com/id/13/delete/MTM.CjL6Fg.REIdVXa-whJS_x8ojQL4RrXnuF4'
@apiSuccessExample {html} Using GET:
<!DOCTYPE html>
<html>
<head>
<script>
if (confirm('Delete: Are you sure?')) {
xhr = new XMLHttpRequest;
xhr.open('POST', window.location.href);
xhr.send(null);
xhr.onload = function() {
window.location.href = "https://example.com/example-thread/#isso-13";
};
}
</script>
@apiSuccessExample Using POST:
Yo
"""
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thread["uri"] + "#isso-%i" % item["id"]
if item is None:
raise NotFound
if request.method == "GET":
modal = (
"<!DOCTYPE html>"
"<html>"
"<head>"
"<script>"
" if (confirm('%s: Are you sure?')) {"
" xhr = new XMLHttpRequest;"
" xhr.open('POST', window.location.href);"
" xhr.send(null);"
" xhr.onload = function() {"
" window.location.href = %s;"
" };"
" }"
"</script>" % (action.capitalize(), json.dumps(link)))
return Response(modal, 200, content_type="text/html")
if action == "activate":
if item['mode'] == 1:
return Response("Already activated", 200)
with self.isso.lock:
self.comments.activate(id)
self.signal("comments.activate", thread, item)
return Response("Yo", 200)
elif action == "edit":
data = request.get_json()
with self.isso.lock:
rv = self.comments.update(id, data)
for key in set(rv.keys()) - API.FIELDS:
rv.pop(key)
self.signal("comments.edit", rv)
return JSON(rv, 200)
else:
with self.isso.lock:
self.comments.delete(id)
self.cache.delete(
'hash', (item['email'] or item['remote_addr']).encode('utf-8'))
self.signal("comments.delete", id)
return Response("Yo", 200)
"""
@api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.
@apiUse plainParam
@apiParam {number} [limit]
The maximum number of returned top-level comments. Omit for unlimited results.
@apiParam {number} [nested_limit]
The maximum number of returned nested comments per commint. Omit for unlimited results.
@apiParam {number} [after]
Includes only comments were added after the provided UNIX timestamp.
@apiSuccess {number} total_replies
The number of replies if the `limit` parameter was not set. If `after` is set to `X`, this is the number of comments that were created after `X`. So setting `after` may change this value!
@apiSuccess {Object[]} replies
The list of comments. Each comment also has the `total_replies`, `replies`, `id` and `hidden_replies` properties to represent nested comments.
@apiSuccess {number} id
Id of the comment `replies` is the list of replies of. `null` for the list of toplevel comments.
@apiSuccess {number} hidden_replies
The number of comments that were ommited from the results because of the `limit` request parameter. Usually, this will be `total_replies` - `limit`.
@apiExample {curl} Get 2 comments with 5 responses:
curl 'https://comments.example.com/?uri=/thread/&limit=2&nested_limit=5'
@apiSuccessExample Example reponse:
{
"total_replies": 14,
"replies": [
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.732863,
"text": "<p>Hello, World!</p>",
"total_replies": 1,
"hidden_replies": 0,
"dislikes": 2,
"modified": null,
"mode": 1,
"replies": [
{
"website": null,
"author": null,
"parent": 1,
"created": 1464818460.769638,
"text": "<p>Hi, now some Markdown: <em>Italic</em>, <strong>bold</strong>, <code>monospace</code>.</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"hash": "2af4e1a6c96a",
"id": 2,
"likes": 2
}
],
"hash": "1cb6cc0309a2",
"id": 1,
"likes": 2
},
{
"website": null,
"author": null,
"parent": null,
"created": 1464818460.80574,
"text": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium at commodi cum deserunt dolore, error fugiat harum incidunt, ipsa ipsum mollitia nam provident rerum sapiente suscipit tempora vitae? Est, qui?</p>",
"total_replies": 0,
"hidden_replies": 0,
"dislikes": 0,
"modified": null,
"mode": 1,
"replies": [],
"hash": "1cb6cc0309a2",
"id": 3,
"likes": 0
},
"id": null,
"hidden_replies": 12
}
"""
@requires(str, 'uri')
def fetch(self, environ, request, uri):
args = {
'uri': uri,
'after': request.args.get('after', 0)
}
try:
args['limit'] = int(request.args.get('limit'))
except TypeError:
args['limit'] = None
except ValueError:
return BadRequest("limit should be integer")
if request.args.get('parent') is not None:
try:
args['parent'] = int(request.args.get('parent'))
root_id = args['parent']
except ValueError:
return BadRequest("parent should be integer")
else:
args['parent'] = None
root_id = None
plain = request.args.get('plain', '0') == '0'
reply_counts = self.comments.reply_count(uri, after=args['after'])
if args['limit'] == 0:
root_list = []
else:
root_list = list(self.comments.fetch(**args))
if root_id not in reply_counts:
reply_counts[root_id] = 0
try:
nested_limit = int(request.args.get('nested_limit'))
except TypeError:
nested_limit = None
except ValueError:
return BadRequest("nested_limit should be integer")
rv = {
'id': root_id,
'total_replies': reply_counts[root_id],
'hidden_replies': reply_counts[root_id] - len(root_list),
'replies': self._process_fetched_list(root_list, plain)
}
# We are only checking for one level deep comments
if root_id is None:
for comment in rv['replies']:
if comment['id'] in reply_counts:
comment['total_replies'] = reply_counts[comment['id']]
if nested_limit is not None:
if nested_limit > 0:
args['parent'] = comment['id']
args['limit'] = nested_limit
replies = list(self.comments.fetch(**args))
else:
replies = []
else:
args['parent'] = comment['id']
replies = list(self.comments.fetch(**args))
else:
comment['total_replies'] = 0
replies = []
comment['hidden_replies'] = comment['total_replies'] - \
len(replies)
comment['replies'] = self._process_fetched_list(replies, plain)
return JSON(rv, 200)
def _add_gravatar_image(self, item):
if not self.conf.getboolean('gravatar'):
return item
email = item['email'] or item['author'] or ''
email_md5_hash = md5(email)
gravatar_url = self.conf.get('gravatar-url')
item['gravatar_image'] = gravatar_url.format(email_md5_hash)
return item
def _process_fetched_list(self, fetched_list, plain=False):
for item in fetched_list:
key = item['email'] or item['remote_addr']
val = self.cache.get('hash', key.encode('utf-8'))
if val is None:
val = self.hash(key)
self.cache.set('hash', key.encode('utf-8'), val)
item['hash'] = val
item = self._add_gravatar_image(item)
for key in set(item.keys()) - API.FIELDS:
item.pop(key)
if plain:
for item in fetched_list:
item['text'] = self.isso.render(item['text'])
return fetched_list
"""
@apiDefine likeResponse
@apiSuccess {number} likes
The (new) number of likes on the comment.
@apiSuccess {number} dislikes
The (new) number of dislikes on the comment.
"""
"""
@api {post} /id/:id/like like
@apiGroup Comment
@apiDescription
Puts a “like” on a comment. The author of a comment cannot like its own comment.
@apiParam {number} id
The id of the comment to like.
@apiExample {curl} Like comment with id 23:
curl -X POST 'https://comments.example.com/id/23/like'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 5,
"dislikes": 2
}
"""
@xhr
def like(self, environ, request, id):
nv = self.comments.vote(True, id, self._remote_addr(request))
return JSON(nv, 200)
"""
@api {post} /id/:id/dislike dislike
@apiGroup Comment
@apiDescription
Puts a “dislike” on a comment. The author of a comment cannot dislike its own comment.
@apiParam {number} id
The id of the comment to dislike.
@apiExample {curl} Dislike comment with id 23:
curl -X POST 'https://comments.example.com/id/23/dislike'
@apiUse likeResponse
@apiSuccessExample Example response
{
"likes": 4,
"dislikes": 3
}
"""
@xhr
def dislike(self, environ, request, id):
nv = self.comments.vote(False, id, self._remote_addr(request))
return JSON(nv, 200)
# TODO: remove someday (replaced by :func:`counts`)
@requires(str, 'uri')
def count(self, environ, request, uri):
rv = self.comments.count(uri)[0]
if rv == 0:
raise NotFound
return JSON(rv, 200)
"""
@api {post} /count count comments
@apiGroup Thread
@apiDescription
Counts the number of comments on multiple threads. The requestor provides a list of thread uris. The number of comments on each thread is returned as a list, in the same order as the threads were requested. The counts include comments that are reponses to comments.
@apiExample {curl} get the count of 5 threads:
curl 'https://comments.example.com/count' -d '["/blog/firstPost.html", "/blog/controversalPost.html", "/blog/howToCode.html", "/blog/boringPost.html", "/blog/isso.html"]
@apiSuccessExample Counts of 5 threads:
[2, 18, 4, 0, 3]
"""
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
"""
@api {get} /feed Atom feed for comments
@apiGroup Thread
@apiDescription
Provide an Atom feed for the given thread.
"""
@requires(str, 'uri')
def feed(self, environ, request, uri):
conf = self.isso.conf.section("rss")
if not conf.get('base'):
raise NotFound
args = {
'uri': uri,
'order_by': 'id',
'asc': 0,
'limit': conf.getint('limit')
}
try:
args['limit'] = max(int(request.args.get('limit')), args['limit'])
except TypeError:
pass
except ValueError:
return BadRequest("limit should be integer")
comments = self.comments.fetch(**args)
base = conf.get('base').rstrip('/')
hostname = urlparse(base).netloc
# Let's build an Atom feed.
# RFC 4287: https://tools.ietf.org/html/rfc4287
# RFC 4685: https://tools.ietf.org/html/rfc4685 (threading extensions)
# For IDs: http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
feed = ET.Element('feed', {
'xmlns': 'http://www.w3.org/2005/Atom',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0'
})
# For feed ID, we would use thread ID, but we may not have
# one. Therefore, we use the URI. We don't have a year
# either...
id = ET.SubElement(feed, 'id')
id.text = 'tag:{hostname},2018:/isso/thread{uri}'.format(
hostname=hostname, uri=uri)
# For title, we don't have much either. Be pretty generic.
title = ET.SubElement(feed, 'title')
title.text = 'Comments for {hostname}{uri}'.format(
hostname=hostname, uri=uri)
comment0 = None
for comment in comments:
if comment0 is None:
comment0 = comment
entry = ET.SubElement(feed, 'entry')
# We don't use a real date in ID either to help with
# threading.
id = ET.SubElement(entry, 'id')
id.text = 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['id'])
title = ET.SubElement(entry, 'title')
title.text = 'Comment #{}'.format(comment['id'])
updated = ET.SubElement(entry, 'updated')
updated.text = '{}Z'.format(datetime.fromtimestamp(
comment['modified'] or comment['created']).isoformat())
author = ET.SubElement(entry, 'author')
name = ET.SubElement(author, 'name')
name.text = comment['author']
ET.SubElement(entry, 'link', {
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['id'])
})
content = ET.SubElement(entry, 'content', {
'type': 'html',
})
content.text = self.isso.render(comment['text'])
if comment['parent']:
ET.SubElement(entry, 'thr:in-reply-to', {
'ref': 'tag:{hostname},2018:/isso/{tid}/{id}'.format(
hostname=hostname,
tid=comment['tid'],
id=comment['parent']),
'href': '{base}{uri}#isso-{id}'.format(
base=base,
uri=uri, id=comment['parent'])
})
# Updated is mandatory. If we have comments, we use the date
# of last modification of the first one (which is the last
# one). Otherwise, we use a fixed date.
updated = ET.Element('updated')
if comment0 is None:
updated.text = '1970-01-01T01:00:00Z'
else:
updated.text = datetime.fromtimestamp(
comment0['modified'] or comment0['created']).isoformat()
updated.text += 'Z'
feed.insert(0, updated)
output = StringIO()
ET.ElementTree(feed).write(output,
encoding='utf-8',
xml_declaration=True)
response = XML(output.getvalue(), 200)
# Add an etag/last-modified value for caching purpose
if comment0 is None:
response.set_etag('empty')
response.last_modified = 0
else:
response.set_etag('{tid}-{id}'.format(**comment0))
response.last_modified = comment0['modified'] or comment0['created']
return response.make_conditional(request)
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
def demo(self, env, req):
return redirect(
get_current_url(env, strip_querystring=True) + '/index.html'
)
def login(self, env, req):
if not self.isso.conf.getboolean("admin", "enabled"):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('disabled.html', isso_host_script=isso_host_script)
data = req.form
password = self.isso.conf.get("admin", "password")
if data['password'] and data['password'] == password:
response = redirect(re.sub(
r'/login$',
'/admin',
get_current_url(env, strip_querystring=True)
))
cookie = self.create_cookie(value=self.isso.sign({"logged": True}),
expires=datetime.now() + timedelta(1))
response.headers.add("Set-Cookie", cookie("admin-session"))
response.headers.add("X-Set-Cookie", cookie("isso-admin-session"))
return response
else:
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
return render_template('login.html', isso_host_script=isso_host_script)
def admin(self, env, req):
isso_host_script = self.isso.conf.get("server", "public-endpoint") or local.host
if not self.isso.conf.getboolean("admin", "enabled"):
return render_template('disabled.html', isso_host_script=isso_host_script)
try:
data = self.isso.unsign(req.cookies.get('admin-session', ''),
max_age=60 * 60 * 24)
except BadSignature:
return render_template('login.html', isso_host_script=isso_host_script)
if not data or not data['logged']:
return render_template('login.html', isso_host_script=isso_host_script)
page_size = 100
page = int(req.args.get('page', 0))
order_by = req.args.get('order_by', 'created')
asc = int(req.args.get('asc', 0))
mode = int(req.args.get('mode', 2))
comments = self.comments.fetchall(mode=mode, page=page,
limit=page_size,
order_by=order_by,
asc=asc)
comments_enriched = []
for comment in list(comments):
comment['hash'] = self.isso.sign(comment['id'])
comments_enriched.append(comment)
comment_mode_count = self.comments.count_modes()
max_page = int(sum(comment_mode_count.values()) / 100)
return render_template('admin.html', comments=comments_enriched,
page=int(page), mode=int(mode),
conf=self.conf, max_page=max_page,
counts=comment_mode_count,
order_by=order_by, asc=asc,
isso_host_script=isso_host_script)
"""
@api {get} /latest latest
@apiGroup Comment
@apiDescription
Get the latest comments from the system, no matter which thread
@apiParam {number} limit
The quantity of last comments to retrieve
@apiExample {curl} Get the latest 5 comments
curl 'https://comments.example.com/latest?limit=5'
@apiUse commentResponse
@apiSuccessExample Example result:
[
{
"website": null,
"uri": "/some",
"author": null,
"parent": null,
"created": 1464912312.123416,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 3,
"likes": 1
},
{
"website": null,
"uri": "/other",
"author": null,
"parent": null,
"created": 1464914341.312426,
"text": " <p>I want to use MySQL</p>",
"dislikes": 0,
"modified": null,
"mode": 1,
"id": 4,
"likes": 0
}
]
"""
def latest(self, environ, request):
# if the feature is not allowed, don't present the endpoint
if not self.conf.getboolean("latest-enabled"):
return NotFound()
# get and check the limit
bad_limit_msg = "Query parameter 'limit' is mandatory (integer, >0)"
try:
limit = int(request.args['limit'])
except (KeyError, ValueError):
return BadRequest(bad_limit_msg)
if limit <= 0:
return BadRequest(bad_limit_msg)
# retrieve the latest N comments from the DB
all_comments_gen = self.comments.fetchall(limit=None, order_by='created', mode='1')
comments = collections.deque(all_comments_gen, maxlen=limit)
# prepare a special set of fields (except text which is rendered specifically)
fields = {
'author',
'created',
'dislikes',
'id',
'likes',
'mode',
'modified',
'parent',
'text',
'uri',
'website',
}
# process the retrieved comments and build results
result = []
for comment in comments:
processed = {key: comment[key] for key in fields}
processed['text'] = self.isso.render(comment['text'])
result.append(processed)
return JSON(result, 200)
| fluffy-critter | 57aa12699a1338820c9ec34ebbae01d687d69c9f | 5f3bf4fb8e481e09259e8fdf53995fca3461ad59 | Sure, but that should also be a separate PR :) | jelmer | 111 |
ceph/ceph-ansible | 7,380 | Collocated mgr with mon fails to start on RHEL 8.7 | With podman version podman-3:4.2.0-4.module+el8.7.0+17064+3b31f55c and later, when mgr fails to start if mon is already running. This is a workaround until podman is fixed.
Closes: https://bugzilla.redhat.com/show_bug.cgi?id=2169767
Closes: #7365
Signed-off-by: Teoman ONAY <tonay@ibm.com> | null | 2023-02-07 13:58:10+00:00 | 2023-02-19 00:03:04+00:00 | roles/ceph-nfs/templates/ceph-nfs.service.j2 | [Unit]
Description=NFS-Ganesha file server
Documentation=http://github.com/nfs-ganesha/nfs-ganesha/wiki
{% if container_binary == 'docker' %}
After=docker.service network-online.target local-fs.target time-sync.target
Requires=docker.service
{% else %}
After=network-online.target local-fs.target time-sync.target
{% endif %}
Wants=network-online.target local-fs.target time-sync.target
[Service]
EnvironmentFile=-/etc/environment
{% if container_binary == 'podman' %}
ExecStartPre=-/usr/bin/rm -f /%t/%n-pid /%t/%n-cid
ExecStartPre=-/usr/bin/{{ container_binary }} rm --storage ceph-nfs-%i
ExecStartPre=-/usr/bin/mkdir -p /var/log/ceph /var/log/ganesha
{% endif %}
ExecStartPre=-/usr/bin/{{ container_binary }} rm ceph-nfs-%i
ExecStartPre={{ '/bin/mkdir' if ansible_facts['os_family'] == 'Debian' else '/usr/bin/mkdir' }} -p /etc/ceph /etc/ganesha /var/lib/nfs/ganesha /var/log/ganesha
ExecStart=/usr/bin/{{ container_binary }} run --rm --net=host \
{% if container_binary == 'podman' %}
-d --log-driver journald --conmon-pidfile /%t/%n-pid --cidfile /%t/%n-cid \
{% endif %}
--pids-limit={{ 0 if container_binary == 'podman' else -1 }} \
-v /var/lib/ceph:/var/lib/ceph:z \
-v /etc/ceph:/etc/ceph:z \
-v /var/lib/nfs/ganesha:/var/lib/nfs/ganesha:z \
-v /etc/ganesha:/etc/ganesha:z \
-v /var/run/ceph:/var/run/ceph:z \
-v /var/log/ceph:/var/log/ceph:z \
-v /var/log/ganesha:/var/log/ganesha:z \
{% if ceph_nfs_dynamic_exports | bool %}
--privileged \
-v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket \
{% endif -%}
-v /etc/localtime:/etc/localtime:ro \
-e CLUSTER={{ cluster }} \
-e CEPH_DAEMON=NFS \
-e CONTAINER_IMAGE={{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
{{ ceph_nfs_docker_extra_env }} \
--name=ceph-nfs-{{ ceph_nfs_service_suffix | default(ansible_facts['hostname']) }} \
{{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }}
{% if container_binary == 'podman' %}
ExecStop=-/usr/bin/sh -c "/usr/bin/{{ container_binary }} rm -f `cat /%t/%n-cid`"
{% else %}
ExecStopPost=-/usr/bin/{{ container_binary }} stop ceph-nfs-%i
{% endif %}
KillMode=none
Restart=always
RestartSec=10s
TimeoutStartSec=120
TimeoutStopSec=15
{% if container_binary == 'podman' %}
Type=forking
PIDFile=/%t/%n-pid
{% endif %}
[Install]
WantedBy=multi-user.target
| [Unit]
Description=NFS-Ganesha file server
Documentation=http://github.com/nfs-ganesha/nfs-ganesha/wiki
{% if container_binary == 'docker' %}
After=docker.service network-online.target local-fs.target time-sync.target
Requires=docker.service
{% else %}
After=network-online.target local-fs.target time-sync.target
{% endif %}
Wants=network-online.target local-fs.target time-sync.target
[Service]
EnvironmentFile=-/etc/environment
{% if container_binary == 'podman' %}
ExecStartPre=-/usr/bin/rm -f /%t/%n-pid /%t/%n-cid
ExecStartPre=-/usr/bin/{{ container_binary }} rm --storage ceph-nfs-%i
ExecStartPre=-/usr/bin/mkdir -p /var/log/ceph /var/log/ganesha
{% endif %}
ExecStartPre=-/usr/bin/{{ container_binary }} rm ceph-nfs-%i
ExecStartPre={{ '/bin/mkdir' if ansible_facts['os_family'] == 'Debian' else '/usr/bin/mkdir' }} -p /etc/ceph /etc/ganesha /var/lib/nfs/ganesha /var/log/ganesha
ExecStart=/usr/bin/{{ container_binary }} run --rm --net=host \
{% if container_binary == 'podman' %}
-d --log-driver journald --conmon-pidfile /%t/%n-pid --cidfile /%t/%n-cid \
{% endif %}
--pids-limit={{ 0 if container_binary == 'podman' else -1 }} \
-v /var/lib/ceph/bootstrap-rgw/:/var/lib/ceph/bootstrap-rgw:z \
-v /etc/ceph:/etc/ceph:z \
-v /var/lib/nfs/ganesha:/var/lib/nfs/ganesha:z \
-v /etc/ganesha:/etc/ganesha:z \
-v /var/run/ceph:/var/run/ceph:z \
-v /var/log/ceph:/var/log/ceph:z \
-v /var/log/ganesha:/var/log/ganesha:z \
{% if ceph_nfs_dynamic_exports | bool %}
--privileged \
-v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket \
{% endif -%}
-v /etc/localtime:/etc/localtime:ro \
-e CLUSTER={{ cluster }} \
-e CEPH_DAEMON=NFS \
-e CONTAINER_IMAGE={{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
{{ ceph_nfs_docker_extra_env }} \
--name=ceph-nfs-{{ ceph_nfs_service_suffix | default(ansible_facts['hostname']) }} \
{{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }}
{% if container_binary == 'podman' %}
ExecStop=-/usr/bin/sh -c "/usr/bin/{{ container_binary }} rm -f `cat /%t/%n-cid`"
{% else %}
ExecStopPost=-/usr/bin/{{ container_binary }} stop ceph-nfs-%i
{% endif %}
KillMode=none
Restart=always
RestartSec=10s
TimeoutStartSec=120
TimeoutStopSec=15
{% if container_binary == 'podman' %}
Type=forking
PIDFile=/%t/%n-pid
{% endif %}
[Install]
WantedBy=multi-user.target
| asm0deuz | e47288ef6c23820c4fa50835574169233cd06b12 | 637ca81c9cf801e4d1d125dc8a2492b90fd78eea | ```suggestion
-v /var/lib/ceph/bootstrap-rgw/:/var/lib/ceph/bootstrap-rgw:z \
``` | guits | 0 |
ceph/ceph-ansible | 7,355 | Initialize rbd pool at pool creation | When creating a RBD pool it needs to be initialized as per documentation[1] Modified (pre_)generate_ceph_cmd to make it usable with rbd command as well
[1]https://docs.ceph.com/en/latest/rbd/rados-rbd-cmds/#create-a-block-device-pool
Signed-off-by: Teoman ONAY <tonay@redhat.com> | null | 2022-12-02 09:11:22+00:00 | 2023-01-18 13:13:04+00:00 | library/ceph_osd.py | # Copyright 2020, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.ca_common import exit_module, generate_ceph_cmd, is_containerized # noqa: E501
except ImportError:
from module_utils.ca_common import exit_module, generate_ceph_cmd, is_containerized # noqa: E501
import datetime
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: ceph_osd
short_description: Manage Ceph OSD state
version_added: "2.8"
description:
- Manage Ceph OSD state
options:
ids:
description:
- The ceph OSD id(s).
required: true
cluster:
description:
- The ceph cluster name.
required: false
default: ceph
state:
description:
- The ceph OSD state.
required: true
choices: ['destroy', 'down', 'in', 'out', 'purge', 'rm']
author:
- Dimitri Savineau <dsavinea@redhat.com>
'''
EXAMPLES = '''
- name: destroy OSD 42
ceph_osd:
ids: 42
state: destroy
- name: set multiple OSDs down
ceph_osd:
ids: [0, 1, 3]
state: down
- name: set OSD 42 in
ceph_osd:
ids: 42
state: in
- name: set OSD 42 out
ceph_osd:
ids: 42
state: out
- name: purge OSD 42
ceph_osd:
ids: 42
state: purge
- name: rm OSD 42
ceph_osd:
ids: 42
state: rm
'''
RETURN = '''# '''
def main():
module = AnsibleModule(
argument_spec=dict(
ids=dict(type='list', required=True),
cluster=dict(type='str', required=False, default='ceph'),
state=dict(type='str', required=True, choices=['destroy', 'down', 'in', 'out', 'purge', 'rm']), # noqa: E501
),
supports_check_mode=True,
)
ids = module.params.get('ids')
cluster = module.params.get('cluster')
state = module.params.get('state')
if state in ['destroy', 'purge'] and len(ids) > 1:
module.fail_json(msg='destroy and purge only support one OSD at at time', rc=1) # noqa: E501
startd = datetime.datetime.now()
container_image = is_containerized()
cmd = generate_ceph_cmd(['osd', state], ids, cluster=cluster, container_image=container_image) # noqa: E501
if state in ['destroy', 'purge']:
cmd.append('--yes-i-really-mean-it')
if module.check_mode:
exit_module(
module=module,
out='',
rc=0,
cmd=cmd,
err='',
startd=startd,
changed=False
)
else:
rc, out, err = module.run_command(cmd)
changed = True
if state in ['down', 'in', 'out'] and 'marked' not in err:
changed = False
exit_module(
module=module,
out=out,
rc=rc,
cmd=cmd,
err=err,
startd=startd,
changed=changed
)
if __name__ == '__main__':
main()
| # Copyright 2020, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.ca_common import exit_module, generate_cmd, is_containerized # noqa: E501
except ImportError:
from module_utils.ca_common import exit_module, generate_cmd, is_containerized # noqa: E501
import datetime
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: ceph_osd
short_description: Manage Ceph OSD state
version_added: "2.8"
description:
- Manage Ceph OSD state
options:
ids:
description:
- The ceph OSD id(s).
required: true
cluster:
description:
- The ceph cluster name.
required: false
default: ceph
state:
description:
- The ceph OSD state.
required: true
choices: ['destroy', 'down', 'in', 'out', 'purge', 'rm']
author:
- Dimitri Savineau <dsavinea@redhat.com>
'''
EXAMPLES = '''
- name: destroy OSD 42
ceph_osd:
ids: 42
state: destroy
- name: set multiple OSDs down
ceph_osd:
ids: [0, 1, 3]
state: down
- name: set OSD 42 in
ceph_osd:
ids: 42
state: in
- name: set OSD 42 out
ceph_osd:
ids: 42
state: out
- name: purge OSD 42
ceph_osd:
ids: 42
state: purge
- name: rm OSD 42
ceph_osd:
ids: 42
state: rm
'''
RETURN = '''# '''
def main():
module = AnsibleModule(
argument_spec=dict(
ids=dict(type='list', required=True),
cluster=dict(type='str', required=False, default='ceph'),
state=dict(type='str', required=True, choices=['destroy', 'down', 'in', 'out', 'purge', 'rm']), # noqa: E501
),
supports_check_mode=True,
)
ids = module.params.get('ids')
cluster = module.params.get('cluster')
state = module.params.get('state')
if state in ['destroy', 'purge'] and len(ids) > 1:
module.fail_json(msg='destroy and purge only support one OSD at at time', rc=1) # noqa: E501
startd = datetime.datetime.now()
container_image = is_containerized()
cmd = generate_cmd(sub_cmd=['osd', state], args=ids, cluster=cluster, container_image=container_image) # noqa: E501
if state in ['destroy', 'purge']:
cmd.append('--yes-i-really-mean-it')
if module.check_mode:
exit_module(
module=module,
out='',
rc=0,
cmd=cmd,
err='',
startd=startd,
changed=False
)
else:
rc, out, err = module.run_command(cmd)
changed = True
if state in ['down', 'in', 'out'] and 'marked' not in err:
changed = False
exit_module(
module=module,
out=out,
rc=rc,
cmd=cmd,
err=err,
startd=startd,
changed=changed
)
if __name__ == '__main__':
main()
| asm0deuz | e5ad1953dccf7463507b932b04a00a17f3c8d81e | c39bbc3deaf7a02d36daa39d752e91e94afb3c3e | ```suggestion
cmd = generate_cmd(['osd', state], ids, cluster=cluster, container_image=container_image) # noqa: E501
``` | guits | 1 |
ceph/ceph-ansible | 7,355 | Initialize rbd pool at pool creation | When creating a RBD pool it needs to be initialized as per documentation[1] Modified (pre_)generate_ceph_cmd to make it usable with rbd command as well
[1]https://docs.ceph.com/en/latest/rbd/rados-rbd-cmds/#create-a-block-device-pool
Signed-off-by: Teoman ONAY <tonay@redhat.com> | null | 2022-12-02 09:11:22+00:00 | 2023-01-18 13:13:04+00:00 | library/ceph_osd_flag.py | # Copyright 2020, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.ca_common import exit_module, \
generate_ceph_cmd, \
is_containerized
except ImportError:
from module_utils.ca_common import exit_module, \
generate_ceph_cmd, \
is_containerized
import datetime
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: ceph_osd_flag
short_description: Manage Ceph OSD flag
version_added: "2.8"
description:
- Manage Ceph OSD flag
options:
name:
description:
- name of the ceph OSD flag.
required: true
choices: ['noup', 'nodown', 'noout', 'nobackfill', 'norebalance',
'norecover', 'noscrub', 'nodeep-scrub']
cluster:
description:
- The ceph cluster name.
required: false
default: ceph
state:
description:
- If 'present' is used, the module sets the OSD flag.
If 'absent' is used, the module will unset the OSD flag.
required: false
choices: ['present', 'absent']
default: present
author:
- Dimitri Savineau <dsavinea@redhat.com>
'''
EXAMPLES = '''
- name: set noup OSD flag
ceph_osd_flag:
name: noup
- name: unset multiple OSD flags
ceph_osd_flag:
name: '{{ item }}'
state: absent
loop:
- 'noup'
- 'norebalance'
'''
RETURN = '''# '''
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True, choices=['noup', 'nodown', 'noout', 'nobackfill', 'norebalance', 'norecover', 'noscrub', 'nodeep-scrub']), # noqa: E501
cluster=dict(type='str', required=False, default='ceph'),
state=dict(type='str', required=False, default='present', choices=['present', 'absent']), # noqa: E501
),
supports_check_mode=True,
)
name = module.params.get('name')
cluster = module.params.get('cluster')
state = module.params.get('state')
startd = datetime.datetime.now()
container_image = is_containerized()
if state == 'present':
cmd = generate_ceph_cmd(['osd', 'set'], [name], cluster=cluster, container_image=container_image) # noqa: E501
else:
cmd = generate_ceph_cmd(['osd', 'unset'], [name], cluster=cluster, container_image=container_image) # noqa: E501
if module.check_mode:
exit_module(
module=module,
out='',
rc=0,
cmd=cmd,
err='',
startd=startd,
changed=False
)
else:
rc, out, err = module.run_command(cmd)
exit_module(
module=module,
out=out,
rc=rc,
cmd=cmd,
err=err,
startd=startd,
changed=True
)
if __name__ == '__main__':
main()
| # Copyright 2020, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.ca_common import exit_module, \
generate_cmd, \
is_containerized
except ImportError:
from module_utils.ca_common import exit_module, \
generate_cmd, \
is_containerized
import datetime
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: ceph_osd_flag
short_description: Manage Ceph OSD flag
version_added: "2.8"
description:
- Manage Ceph OSD flag
options:
name:
description:
- name of the ceph OSD flag.
required: true
choices: ['noup', 'nodown', 'noout', 'nobackfill', 'norebalance',
'norecover', 'noscrub', 'nodeep-scrub']
cluster:
description:
- The ceph cluster name.
required: false
default: ceph
state:
description:
- If 'present' is used, the module sets the OSD flag.
If 'absent' is used, the module will unset the OSD flag.
required: false
choices: ['present', 'absent']
default: present
author:
- Dimitri Savineau <dsavinea@redhat.com>
'''
EXAMPLES = '''
- name: set noup OSD flag
ceph_osd_flag:
name: noup
- name: unset multiple OSD flags
ceph_osd_flag:
name: '{{ item }}'
state: absent
loop:
- 'noup'
- 'norebalance'
'''
RETURN = '''# '''
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True, choices=['noup', 'nodown', 'noout', 'nobackfill', 'norebalance', 'norecover', 'noscrub', 'nodeep-scrub']), # noqa: E501
cluster=dict(type='str', required=False, default='ceph'),
state=dict(type='str', required=False, default='present', choices=['present', 'absent']), # noqa: E501
),
supports_check_mode=True,
)
name = module.params.get('name')
cluster = module.params.get('cluster')
state = module.params.get('state')
startd = datetime.datetime.now()
container_image = is_containerized()
if state == 'present':
cmd = generate_cmd(sub_cmd=['osd', 'set'], args=[name], cluster=cluster, container_image=container_image) # noqa: E501
else:
cmd = generate_cmd(sub_cmd=['osd', 'unset'], args=[name], cluster=cluster, container_image=container_image) # noqa: E501
if module.check_mode:
exit_module(
module=module,
out='',
rc=0,
cmd=cmd,
err='',
startd=startd,
changed=False
)
else:
rc, out, err = module.run_command(cmd)
exit_module(
module=module,
out=out,
rc=rc,
cmd=cmd,
err=err,
startd=startd,
changed=True
)
if __name__ == '__main__':
main()
| asm0deuz | e5ad1953dccf7463507b932b04a00a17f3c8d81e | c39bbc3deaf7a02d36daa39d752e91e94afb3c3e | ```suggestion
cmd = generate_cmd(['osd', 'set'], [name], cluster=cluster, container_image=container_image) # noqa: E501
``` | guits | 2 |
ceph/ceph-ansible | 7,355 | Initialize rbd pool at pool creation | When creating a RBD pool it needs to be initialized as per documentation[1] Modified (pre_)generate_ceph_cmd to make it usable with rbd command as well
[1]https://docs.ceph.com/en/latest/rbd/rados-rbd-cmds/#create-a-block-device-pool
Signed-off-by: Teoman ONAY <tonay@redhat.com> | null | 2022-12-02 09:11:22+00:00 | 2023-01-18 13:13:04+00:00 | library/ceph_osd_flag.py | # Copyright 2020, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.ca_common import exit_module, \
generate_ceph_cmd, \
is_containerized
except ImportError:
from module_utils.ca_common import exit_module, \
generate_ceph_cmd, \
is_containerized
import datetime
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: ceph_osd_flag
short_description: Manage Ceph OSD flag
version_added: "2.8"
description:
- Manage Ceph OSD flag
options:
name:
description:
- name of the ceph OSD flag.
required: true
choices: ['noup', 'nodown', 'noout', 'nobackfill', 'norebalance',
'norecover', 'noscrub', 'nodeep-scrub']
cluster:
description:
- The ceph cluster name.
required: false
default: ceph
state:
description:
- If 'present' is used, the module sets the OSD flag.
If 'absent' is used, the module will unset the OSD flag.
required: false
choices: ['present', 'absent']
default: present
author:
- Dimitri Savineau <dsavinea@redhat.com>
'''
EXAMPLES = '''
- name: set noup OSD flag
ceph_osd_flag:
name: noup
- name: unset multiple OSD flags
ceph_osd_flag:
name: '{{ item }}'
state: absent
loop:
- 'noup'
- 'norebalance'
'''
RETURN = '''# '''
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True, choices=['noup', 'nodown', 'noout', 'nobackfill', 'norebalance', 'norecover', 'noscrub', 'nodeep-scrub']), # noqa: E501
cluster=dict(type='str', required=False, default='ceph'),
state=dict(type='str', required=False, default='present', choices=['present', 'absent']), # noqa: E501
),
supports_check_mode=True,
)
name = module.params.get('name')
cluster = module.params.get('cluster')
state = module.params.get('state')
startd = datetime.datetime.now()
container_image = is_containerized()
if state == 'present':
cmd = generate_ceph_cmd(['osd', 'set'], [name], cluster=cluster, container_image=container_image) # noqa: E501
else:
cmd = generate_ceph_cmd(['osd', 'unset'], [name], cluster=cluster, container_image=container_image) # noqa: E501
if module.check_mode:
exit_module(
module=module,
out='',
rc=0,
cmd=cmd,
err='',
startd=startd,
changed=False
)
else:
rc, out, err = module.run_command(cmd)
exit_module(
module=module,
out=out,
rc=rc,
cmd=cmd,
err=err,
startd=startd,
changed=True
)
if __name__ == '__main__':
main()
| # Copyright 2020, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.ca_common import exit_module, \
generate_cmd, \
is_containerized
except ImportError:
from module_utils.ca_common import exit_module, \
generate_cmd, \
is_containerized
import datetime
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: ceph_osd_flag
short_description: Manage Ceph OSD flag
version_added: "2.8"
description:
- Manage Ceph OSD flag
options:
name:
description:
- name of the ceph OSD flag.
required: true
choices: ['noup', 'nodown', 'noout', 'nobackfill', 'norebalance',
'norecover', 'noscrub', 'nodeep-scrub']
cluster:
description:
- The ceph cluster name.
required: false
default: ceph
state:
description:
- If 'present' is used, the module sets the OSD flag.
If 'absent' is used, the module will unset the OSD flag.
required: false
choices: ['present', 'absent']
default: present
author:
- Dimitri Savineau <dsavinea@redhat.com>
'''
EXAMPLES = '''
- name: set noup OSD flag
ceph_osd_flag:
name: noup
- name: unset multiple OSD flags
ceph_osd_flag:
name: '{{ item }}'
state: absent
loop:
- 'noup'
- 'norebalance'
'''
RETURN = '''# '''
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True, choices=['noup', 'nodown', 'noout', 'nobackfill', 'norebalance', 'norecover', 'noscrub', 'nodeep-scrub']), # noqa: E501
cluster=dict(type='str', required=False, default='ceph'),
state=dict(type='str', required=False, default='present', choices=['present', 'absent']), # noqa: E501
),
supports_check_mode=True,
)
name = module.params.get('name')
cluster = module.params.get('cluster')
state = module.params.get('state')
startd = datetime.datetime.now()
container_image = is_containerized()
if state == 'present':
cmd = generate_cmd(sub_cmd=['osd', 'set'], args=[name], cluster=cluster, container_image=container_image) # noqa: E501
else:
cmd = generate_cmd(sub_cmd=['osd', 'unset'], args=[name], cluster=cluster, container_image=container_image) # noqa: E501
if module.check_mode:
exit_module(
module=module,
out='',
rc=0,
cmd=cmd,
err='',
startd=startd,
changed=False
)
else:
rc, out, err = module.run_command(cmd)
exit_module(
module=module,
out=out,
rc=rc,
cmd=cmd,
err=err,
startd=startd,
changed=True
)
if __name__ == '__main__':
main()
| asm0deuz | e5ad1953dccf7463507b932b04a00a17f3c8d81e | c39bbc3deaf7a02d36daa39d752e91e94afb3c3e | ```suggestion
cmd = generate_cmd(['osd', 'unset'], [name], cluster=cluster, container_image=container_image) # noqa: E501
``` | guits | 3 |
ceph/ceph-ansible | 7,355 | Initialize rbd pool at pool creation | When creating a RBD pool it needs to be initialized as per documentation[1] Modified (pre_)generate_ceph_cmd to make it usable with rbd command as well
[1]https://docs.ceph.com/en/latest/rbd/rados-rbd-cmds/#create-a-block-device-pool
Signed-off-by: Teoman ONAY <tonay@redhat.com> | null | 2022-12-02 09:11:22+00:00 | 2023-01-18 13:13:04+00:00 | library/ceph_pool.py | #!/usr/bin/python3
# Copyright 2020, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.ca_common import generate_ceph_cmd, \
pre_generate_ceph_cmd, \
is_containerized, \
exec_command, \
exit_module
except ImportError:
from module_utils.ca_common import generate_ceph_cmd, \
pre_generate_ceph_cmd, \
is_containerized, \
exec_command, \
exit_module
import datetime
import json
import os
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: ceph_pool
author: Guillaume Abrioux <gabrioux@redhat.com>
short_description: Manage Ceph Pools
version_added: "2.8"
description:
- Manage Ceph pool(s) creation, deletion and updates.
options:
cluster:
description:
- The ceph cluster name.
required: false
default: ceph
name:
description:
- name of the Ceph pool
required: true
state:
description:
If 'present' is used, the module creates a pool if it doesn't exist
or update it if it already exists.
If 'absent' is used, the module will simply delete the pool.
If 'list' is used, the module will return all details about the
existing pools. (json formatted).
required: false
choices: ['present', 'absent', 'list']
default: present
size:
description:
- set the replica size of the pool.
required: false
default: 3
min_size:
description:
- set the min_size parameter of the pool.
required: false
default: default to `osd_pool_default_min_size` (ceph)
pg_num:
description:
- set the pg_num of the pool.
required: false
default: default to `osd_pool_default_pg_num` (ceph)
pgp_num:
description:
- set the pgp_num of the pool.
required: false
default: default to `osd_pool_default_pgp_num` (ceph)
pg_autoscale_mode:
description:
- set the pg autoscaler on the pool.
required: false
default: 'on'
target_size_ratio:
description:
- set the target_size_ratio on the pool
required: false
default: None
pool_type:
description:
- set the pool type, either 'replicated' or 'erasure'
required: false
default: 'replicated'
erasure_profile:
description:
- When pool_type = 'erasure', set the erasure profile of the pool
required: false
default: 'default'
rule_name:
description:
- Set the crush rule name assigned to the pool
required: false
default: 'replicated_rule' when pool_type is 'erasure' else None
expected_num_objects:
description:
- Set the expected_num_objects parameter of the pool.
required: false
default: '0'
application:
description:
- Set the pool application on the pool.
required: false
default: None
'''
EXAMPLES = '''
pools:
- { name: foo, size: 3, application: rbd, pool_type: 'replicated',
pg_autoscale_mode: 'on' }
- hosts: all
become: true
tasks:
- name: create a pool
ceph_pool:
name: "{{ item.name }}"
state: present
size: "{{ item.size }}"
application: "{{ item.application }}"
pool_type: "{{ item.pool_type }}"
pg_autoscale_mode: "{{ item.pg_autoscale_mode }}"
with_items: "{{ pools }}"
'''
RETURN = '''# '''
def check_pool_exist(cluster,
name,
user,
user_key,
output_format='json',
container_image=None):
'''
Check if a given pool exists
'''
args = ['stats', name, '-f', output_format]
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def generate_get_config_cmd(param,
cluster,
user,
user_key,
container_image=None):
_cmd = pre_generate_ceph_cmd(container_image=container_image)
args = [
'-n',
user,
'-k',
user_key,
'--cluster',
cluster,
'config',
'get',
'mon.*',
param
]
cmd = _cmd + args
return cmd
def get_application_pool(cluster,
name,
user,
user_key,
output_format='json',
container_image=None):
'''
Get application type enabled on a given pool
'''
args = ['application', 'get', name, '-f', output_format]
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def enable_application_pool(cluster,
name,
application,
user,
user_key,
container_image=None):
'''
Enable application on a given pool
'''
args = ['application', 'enable', name, application]
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def disable_application_pool(cluster,
name,
application,
user,
user_key,
container_image=None):
'''
Disable application on a given pool
'''
args = ['application', 'disable', name,
application, '--yes-i-really-mean-it']
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def get_pool_details(module,
cluster,
name,
user,
user_key,
output_format='json',
container_image=None):
'''
Get details about a given pool
'''
args = ['ls', 'detail', '-f', output_format]
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
rc, cmd, out, err = exec_command(module, cmd)
if rc == 0:
out = [p for p in json.loads(out.strip()) if p['pool_name'] == name][0]
_rc, _cmd, application_pool, _err = exec_command(module,
get_application_pool(cluster, # noqa: E501
name, # noqa: E501
user, # noqa: E501
user_key, # noqa: E501
container_image=container_image)) # noqa: E501
# This is a trick because "target_size_ratio" isn't present at the same
# level in the dict
# ie:
# {
# 'pg_num': 8,
# 'pgp_num': 8,
# 'pg_autoscale_mode': 'on',
# 'options': {
# 'target_size_ratio': 0.1
# }
# }
# If 'target_size_ratio' is present in 'options', we set it, this way we
# end up with a dict containing all needed keys at the same level.
if 'target_size_ratio' in out['options'].keys():
out['target_size_ratio'] = out['options']['target_size_ratio']
else:
out['target_size_ratio'] = None
application = list(json.loads(application_pool.strip()).keys())
if len(application) == 0:
out['application'] = ''
else:
out['application'] = application[0]
return rc, cmd, out, err
def compare_pool_config(user_pool_config, running_pool_details):
'''
Compare user input config pool details with current running pool details
'''
delta = {}
filter_keys = ['pg_num', 'pg_placement_num', 'size',
'pg_autoscale_mode', 'target_size_ratio']
for key in filter_keys:
if (str(running_pool_details[key]) != user_pool_config[key]['value'] and # noqa: E501
user_pool_config[key]['value']):
delta[key] = user_pool_config[key]
if (running_pool_details['application'] !=
user_pool_config['application']['value'] and
user_pool_config['application']['value']):
delta['application'] = {}
delta['application']['new_application'] = user_pool_config['application']['value'] # noqa: E501
# to be improved (for update_pools()...)
delta['application']['value'] = delta['application']['new_application']
delta['application']['old_application'] = running_pool_details['application'] # noqa: E501
return delta
def list_pools(cluster,
user,
user_key,
details,
output_format='json',
container_image=None):
'''
List existing pools
'''
args = ['ls']
if details:
args.append('detail')
args.extend(['-f', output_format])
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def create_pool(cluster,
name,
user,
user_key,
user_pool_config,
container_image=None):
'''
Create a new pool
'''
args = ['create', user_pool_config['pool_name']['value'],
user_pool_config['type']['value']]
if user_pool_config['pg_autoscale_mode']['value'] == 'off':
args.extend(['--pg_num',
user_pool_config['pg_num']['value'],
'--pgp_num',
user_pool_config['pgp_num']['value'] or
user_pool_config['pg_num']['value']])
elif user_pool_config['target_size_ratio']['value']:
args.extend(['--target_size_ratio',
user_pool_config['target_size_ratio']['value']])
if user_pool_config['type']['value'] == 'replicated':
args.extend([user_pool_config['crush_rule']['value'],
'--expected_num_objects',
user_pool_config['expected_num_objects']['value'],
'--autoscale-mode',
user_pool_config['pg_autoscale_mode']['value']])
if (user_pool_config['size']['value'] and
user_pool_config['type']['value'] == "replicated"):
args.extend(['--size', user_pool_config['size']['value']])
elif user_pool_config['type']['value'] == 'erasure':
args.extend([user_pool_config['erasure_profile']['value']])
if user_pool_config['crush_rule']['value']:
args.extend([user_pool_config['crush_rule']['value']])
args.extend(['--expected_num_objects',
user_pool_config['expected_num_objects']['value'],
'--autoscale-mode',
user_pool_config['pg_autoscale_mode']['value']])
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def remove_pool(cluster, name, user, user_key, container_image=None):
'''
Remove a pool
'''
args = ['rm', name, name, '--yes-i-really-really-mean-it']
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def update_pool(module, cluster, name,
user, user_key, delta, container_image=None):
'''
Update an existing pool
'''
report = ""
for key in delta.keys():
if key != 'application':
args = ['set',
name,
delta[key]['cli_set_opt'],
delta[key]['value']]
cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
rc, cmd, out, err = exec_command(module, cmd)
if rc != 0:
return rc, cmd, out, err
else:
rc, cmd, out, err = exec_command(module, disable_application_pool(cluster, name, delta['application']['old_application'], user, user_key, container_image=container_image)) # noqa: E501
if rc != 0:
return rc, cmd, out, err
rc, cmd, out, err = exec_command(module, enable_application_pool(cluster, name, delta['application']['new_application'], user, user_key, container_image=container_image)) # noqa: E501
if rc != 0:
return rc, cmd, out, err
report = report + "\n" + "{} has been updated: {} is now {}".format(name, key, delta[key]['value']) # noqa: E501
out = report
return rc, cmd, out, err
def run_module():
module_args = dict(
cluster=dict(type='str', required=False, default='ceph'),
name=dict(type='str', required=True),
state=dict(type='str', required=False, default='present',
choices=['present', 'absent', 'list']),
details=dict(type='bool', required=False, default=False),
size=dict(type='str', required=False),
min_size=dict(type='str', required=False),
pg_num=dict(type='str', required=False),
pgp_num=dict(type='str', required=False),
pg_autoscale_mode=dict(type='str', required=False, default='on'),
target_size_ratio=dict(type='str', required=False, default=None),
pool_type=dict(type='str', required=False, default='replicated',
choices=['replicated', 'erasure', '1', '3']),
erasure_profile=dict(type='str', required=False, default='default'),
rule_name=dict(type='str', required=False, default=None),
expected_num_objects=dict(type='str', required=False, default="0"),
application=dict(type='str', required=False, default=None),
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
# Gather module parameters in variables
cluster = module.params.get('cluster')
name = module.params.get('name')
state = module.params.get('state')
details = module.params.get('details')
size = module.params.get('size')
min_size = module.params.get('min_size')
pg_num = module.params.get('pg_num')
pgp_num = module.params.get('pgp_num')
pg_autoscale_mode = module.params.get('pg_autoscale_mode')
target_size_ratio = module.params.get('target_size_ratio')
application = module.params.get('application')
if (module.params.get('pg_autoscale_mode').lower() in
['true', 'on', 'yes']):
pg_autoscale_mode = 'on'
elif (module.params.get('pg_autoscale_mode').lower() in
['false', 'off', 'no']):
pg_autoscale_mode = 'off'
else:
pg_autoscale_mode = 'warn'
if module.params.get('pool_type') == '1':
pool_type = 'replicated'
elif module.params.get('pool_type') == '3':
pool_type = 'erasure'
else:
pool_type = module.params.get('pool_type')
if not module.params.get('rule_name'):
rule_name = 'replicated_rule' if pool_type == 'replicated' else None
else:
rule_name = module.params.get('rule_name')
erasure_profile = module.params.get('erasure_profile')
expected_num_objects = module.params.get('expected_num_objects')
user_pool_config = {
'pool_name': {'value': name},
'pg_num': {'value': pg_num, 'cli_set_opt': 'pg_num'},
'pgp_num': {'value': pgp_num, 'cli_set_opt': 'pgp_num'},
'pg_autoscale_mode': {'value': pg_autoscale_mode,
'cli_set_opt': 'pg_autoscale_mode'},
'target_size_ratio': {'value': target_size_ratio,
'cli_set_opt': 'target_size_ratio'},
'application': {'value': application},
'type': {'value': pool_type},
'erasure_profile': {'value': erasure_profile},
'crush_rule': {'value': rule_name, 'cli_set_opt': 'crush_rule'},
'expected_num_objects': {'value': expected_num_objects},
'size': {'value': size, 'cli_set_opt': 'size'},
'min_size': {'value': min_size}
}
if module.check_mode:
module.exit_json(
changed=False,
stdout='',
stderr='',
rc=0,
start='',
end='',
delta='',
)
startd = datetime.datetime.now()
changed = False
# will return either the image name or None
container_image = is_containerized()
user = "client.admin"
keyring_filename = cluster + '.' + user + '.keyring'
user_key = os.path.join("/etc/ceph/", keyring_filename)
if state == "present":
rc, cmd, out, err = exec_command(module,
check_pool_exist(cluster,
name,
user,
user_key,
container_image=container_image)) # noqa: E501
if rc == 0:
running_pool_details = get_pool_details(module,
cluster,
name,
user,
user_key,
container_image=container_image) # noqa: E501
user_pool_config['pg_placement_num'] = {'value': str(running_pool_details[2]['pg_placement_num']), 'cli_set_opt': 'pgp_num'} # noqa: E501
delta = compare_pool_config(user_pool_config,
running_pool_details[2])
if len(delta) > 0:
keys = list(delta.keys())
details = running_pool_details[2]
if details['erasure_code_profile'] and 'size' in keys:
del delta['size']
if details['pg_autoscale_mode'] == 'on':
delta.pop('pg_num', None)
delta.pop('pgp_num', None)
if len(delta) == 0:
out = "Skipping pool {}.\nUpdating either 'size' on an erasure-coded pool or 'pg_num'/'pgp_num' on a pg autoscaled pool is incompatible".format(name) # noqa: E501
else:
rc, cmd, out, err = update_pool(module,
cluster,
name,
user,
user_key,
delta,
container_image=container_image) # noqa: E501
if rc == 0:
changed = True
else:
out = "Pool {} already exists and there is nothing to update.".format(name) # noqa: E501
else:
rc, cmd, out, err = exec_command(module,
create_pool(cluster,
name,
user,
user_key,
user_pool_config=user_pool_config, # noqa: E501
container_image=container_image)) # noqa: E501
if user_pool_config['application']['value']:
rc, _, _, _ = exec_command(module,
enable_application_pool(cluster,
name,
user_pool_config['application']['value'], # noqa: E501
user,
user_key,
container_image=container_image)) # noqa: E501
if user_pool_config['min_size']['value']:
# not implemented yet
pass
changed = True
elif state == "list":
rc, cmd, out, err = exec_command(module,
list_pools(cluster,
name, user,
user_key,
details,
container_image=container_image)) # noqa: E501
if rc != 0:
out = "Couldn't list pool(s) present on the cluster"
elif state == "absent":
rc, cmd, out, err = exec_command(module,
check_pool_exist(cluster,
name, user,
user_key,
container_image=container_image)) # noqa: E501
if rc == 0:
rc, cmd, out, err = exec_command(module,
remove_pool(cluster,
name,
user,
user_key,
container_image=container_image)) # noqa: E501
changed = True
else:
rc = 0
out = "Skipped, since pool {} doesn't exist".format(name)
exit_module(module=module, out=out, rc=rc, cmd=cmd, err=err, startd=startd,
changed=changed)
def main():
run_module()
if __name__ == '__main__':
main()
| #!/usr/bin/python3
# Copyright 2020, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.ca_common import generate_cmd, \
pre_generate_cmd, \
is_containerized, \
exec_command, \
exit_module
except ImportError:
from module_utils.ca_common import generate_cmd, \
pre_generate_cmd, \
is_containerized, \
exec_command, \
exit_module
import datetime
import json
import os
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: ceph_pool
author: Guillaume Abrioux <gabrioux@redhat.com>
short_description: Manage Ceph Pools
version_added: "2.8"
description:
- Manage Ceph pool(s) creation, deletion and updates.
options:
cluster:
description:
- The ceph cluster name.
required: false
default: ceph
name:
description:
- name of the Ceph pool
required: true
state:
description:
If 'present' is used, the module creates a pool if it doesn't exist
or update it if it already exists.
If 'absent' is used, the module will simply delete the pool.
If 'list' is used, the module will return all details about the
existing pools. (json formatted).
required: false
choices: ['present', 'absent', 'list']
default: present
size:
description:
- set the replica size of the pool.
required: false
default: 3
min_size:
description:
- set the min_size parameter of the pool.
required: false
default: default to `osd_pool_default_min_size` (ceph)
pg_num:
description:
- set the pg_num of the pool.
required: false
default: default to `osd_pool_default_pg_num` (ceph)
pgp_num:
description:
- set the pgp_num of the pool.
required: false
default: default to `osd_pool_default_pgp_num` (ceph)
pg_autoscale_mode:
description:
- set the pg autoscaler on the pool.
required: false
default: 'on'
target_size_ratio:
description:
- set the target_size_ratio on the pool
required: false
default: None
pool_type:
description:
- set the pool type, either 'replicated' or 'erasure'
required: false
default: 'replicated'
erasure_profile:
description:
- When pool_type = 'erasure', set the erasure profile of the pool
required: false
default: 'default'
rule_name:
description:
- Set the crush rule name assigned to the pool
required: false
default: 'replicated_rule' when pool_type is 'erasure' else None
expected_num_objects:
description:
- Set the expected_num_objects parameter of the pool.
required: false
default: '0'
application:
description:
- Set the pool application on the pool.
required: false
default: None
'''
EXAMPLES = '''
pools:
- { name: foo, size: 3, application: rbd, pool_type: 'replicated',
pg_autoscale_mode: 'on' }
- hosts: all
become: true
tasks:
- name: create a pool
ceph_pool:
name: "{{ item.name }}"
state: present
size: "{{ item.size }}"
application: "{{ item.application }}"
pool_type: "{{ item.pool_type }}"
pg_autoscale_mode: "{{ item.pg_autoscale_mode }}"
with_items: "{{ pools }}"
'''
RETURN = '''# '''
def check_pool_exist(cluster,
name,
user,
user_key,
output_format='json',
container_image=None):
'''
Check if a given pool exists
'''
args = ['stats', name, '-f', output_format]
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def generate_get_config_cmd(param,
cluster,
user,
user_key,
container_image=None):
_cmd = pre_generate_cmd('ceph', container_image=container_image)
args = [
'-n',
user,
'-k',
user_key,
'--cluster',
cluster,
'config',
'get',
'mon.*',
param
]
cmd = _cmd + args
return cmd
def get_application_pool(cluster,
name,
user,
user_key,
output_format='json',
container_image=None):
'''
Get application type enabled on a given pool
'''
args = ['application', 'get', name, '-f', output_format]
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def enable_application_pool(cluster,
name,
application,
user,
user_key,
container_image=None):
'''
Enable application on a given pool
'''
args = ['application', 'enable', name, application]
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def init_rbd_pool(cluster,
name,
user,
user_key,
container_image=None):
'''
Initialize a rbd pool
'''
args = [name]
cmd = generate_cmd(cmd='rbd',
sub_cmd=['pool', 'init'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def disable_application_pool(cluster,
name,
application,
user,
user_key,
container_image=None):
'''
Disable application on a given pool
'''
args = ['application', 'disable', name,
application, '--yes-i-really-mean-it']
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def get_pool_details(module,
cluster,
name,
user,
user_key,
output_format='json',
container_image=None):
'''
Get details about a given pool
'''
args = ['ls', 'detail', '-f', output_format]
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
rc, cmd, out, err = exec_command(module, cmd)
if rc == 0:
out = [p for p in json.loads(out.strip()) if p['pool_name'] == name][0]
_rc, _cmd, application_pool, _err = exec_command(module,
get_application_pool(cluster, # noqa: E501
name, # noqa: E501
user, # noqa: E501
user_key, # noqa: E501
container_image=container_image)) # noqa: E501
# This is a trick because "target_size_ratio" isn't present at the same
# level in the dict
# ie:
# {
# 'pg_num': 8,
# 'pgp_num': 8,
# 'pg_autoscale_mode': 'on',
# 'options': {
# 'target_size_ratio': 0.1
# }
# }
# If 'target_size_ratio' is present in 'options', we set it, this way we
# end up with a dict containing all needed keys at the same level.
if 'target_size_ratio' in out['options'].keys():
out['target_size_ratio'] = out['options']['target_size_ratio']
else:
out['target_size_ratio'] = None
application = list(json.loads(application_pool.strip()).keys())
if len(application) == 0:
out['application'] = ''
else:
out['application'] = application[0]
return rc, cmd, out, err
def compare_pool_config(user_pool_config, running_pool_details):
'''
Compare user input config pool details with current running pool details
'''
delta = {}
filter_keys = ['pg_num', 'pg_placement_num', 'size',
'pg_autoscale_mode', 'target_size_ratio']
for key in filter_keys:
if (str(running_pool_details[key]) != user_pool_config[key]['value'] and # noqa: E501
user_pool_config[key]['value']):
delta[key] = user_pool_config[key]
if (running_pool_details['application'] !=
user_pool_config['application']['value'] and
user_pool_config['application']['value']):
delta['application'] = {}
delta['application']['new_application'] = user_pool_config['application']['value'] # noqa: E501
# to be improved (for update_pools()...)
delta['application']['value'] = delta['application']['new_application']
delta['application']['old_application'] = running_pool_details['application'] # noqa: E501
return delta
def list_pools(cluster,
user,
user_key,
details,
output_format='json',
container_image=None):
'''
List existing pools
'''
args = ['ls']
if details:
args.append('detail')
args.extend(['-f', output_format])
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def create_pool(cluster,
user,
user_key,
user_pool_config,
container_image=None):
'''
Create a new pool
'''
args = ['create', user_pool_config['pool_name']['value'],
user_pool_config['type']['value']]
if user_pool_config['pg_autoscale_mode']['value'] == 'off':
args.extend(['--pg_num',
user_pool_config['pg_num']['value'],
'--pgp_num',
user_pool_config['pgp_num']['value'] or
user_pool_config['pg_num']['value']])
elif user_pool_config['target_size_ratio']['value']:
args.extend(['--target_size_ratio',
user_pool_config['target_size_ratio']['value']])
if user_pool_config['type']['value'] == 'replicated':
args.extend([user_pool_config['crush_rule']['value'],
'--expected_num_objects',
user_pool_config['expected_num_objects']['value'],
'--autoscale-mode',
user_pool_config['pg_autoscale_mode']['value']])
if (user_pool_config['size']['value'] and
user_pool_config['type']['value'] == "replicated"):
args.extend(['--size', user_pool_config['size']['value']])
elif user_pool_config['type']['value'] == 'erasure':
args.extend([user_pool_config['erasure_profile']['value']])
if user_pool_config['crush_rule']['value']:
args.extend([user_pool_config['crush_rule']['value']])
args.extend(['--expected_num_objects',
user_pool_config['expected_num_objects']['value'],
'--autoscale-mode',
user_pool_config['pg_autoscale_mode']['value']])
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def remove_pool(cluster, name, user, user_key, container_image=None):
'''
Remove a pool
'''
args = ['rm', name, name, '--yes-i-really-really-mean-it']
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
return cmd
def update_pool(module, cluster, name,
user, user_key, delta, container_image=None):
'''
Update an existing pool
'''
report = ""
for key in delta.keys():
if key != 'application':
args = ['set',
name,
delta[key]['cli_set_opt'],
delta[key]['value']]
cmd = generate_cmd(sub_cmd=['osd', 'pool'],
args=args,
cluster=cluster,
user=user,
user_key=user_key,
container_image=container_image)
rc, cmd, out, err = exec_command(module, cmd)
if rc != 0:
return rc, cmd, out, err
else:
rc, cmd, out, err = exec_command(module, disable_application_pool(cluster, name, delta['application']['old_application'], user, user_key, container_image=container_image)) # noqa: E501
if rc != 0:
return rc, cmd, out, err
rc, cmd, out, err = exec_command(module, enable_application_pool(cluster, name, delta['application']['new_application'], user, user_key, container_image=container_image)) # noqa: E501
if rc != 0:
return rc, cmd, out, err
report = report + "\n" + "{} has been updated: {} is now {}".format(name, key, delta[key]['value']) # noqa: E501
out = report
return rc, cmd, out, err
def run_module():
module_args = dict(
cluster=dict(type='str', required=False, default='ceph'),
name=dict(type='str', required=True),
state=dict(type='str', required=False, default='present',
choices=['present', 'absent', 'list']),
details=dict(type='bool', required=False, default=False),
size=dict(type='str', required=False),
min_size=dict(type='str', required=False),
pg_num=dict(type='str', required=False),
pgp_num=dict(type='str', required=False),
pg_autoscale_mode=dict(type='str', required=False, default='on'),
target_size_ratio=dict(type='str', required=False, default=None),
pool_type=dict(type='str', required=False, default='replicated',
choices=['replicated', 'erasure', '1', '3']),
erasure_profile=dict(type='str', required=False, default='default'),
rule_name=dict(type='str', required=False, default=None),
expected_num_objects=dict(type='str', required=False, default="0"),
application=dict(type='str', required=False, default=None),
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
# Gather module parameters in variables
cluster = module.params.get('cluster')
name = module.params.get('name')
state = module.params.get('state')
details = module.params.get('details')
size = module.params.get('size')
min_size = module.params.get('min_size')
pg_num = module.params.get('pg_num')
pgp_num = module.params.get('pgp_num')
pg_autoscale_mode = module.params.get('pg_autoscale_mode')
target_size_ratio = module.params.get('target_size_ratio')
application = module.params.get('application')
if (module.params.get('pg_autoscale_mode').lower() in
['true', 'on', 'yes']):
pg_autoscale_mode = 'on'
elif (module.params.get('pg_autoscale_mode').lower() in
['false', 'off', 'no']):
pg_autoscale_mode = 'off'
else:
pg_autoscale_mode = 'warn'
if module.params.get('pool_type') == '1':
pool_type = 'replicated'
elif module.params.get('pool_type') == '3':
pool_type = 'erasure'
else:
pool_type = module.params.get('pool_type')
if not module.params.get('rule_name'):
rule_name = 'replicated_rule' if pool_type == 'replicated' else None
else:
rule_name = module.params.get('rule_name')
erasure_profile = module.params.get('erasure_profile')
expected_num_objects = module.params.get('expected_num_objects')
user_pool_config = {
'pool_name': {'value': name},
'pg_num': {'value': pg_num, 'cli_set_opt': 'pg_num'},
'pgp_num': {'value': pgp_num, 'cli_set_opt': 'pgp_num'},
'pg_autoscale_mode': {'value': pg_autoscale_mode,
'cli_set_opt': 'pg_autoscale_mode'},
'target_size_ratio': {'value': target_size_ratio,
'cli_set_opt': 'target_size_ratio'},
'application': {'value': application},
'type': {'value': pool_type},
'erasure_profile': {'value': erasure_profile},
'crush_rule': {'value': rule_name, 'cli_set_opt': 'crush_rule'},
'expected_num_objects': {'value': expected_num_objects},
'size': {'value': size, 'cli_set_opt': 'size'},
'min_size': {'value': min_size}
}
if module.check_mode:
module.exit_json(
changed=False,
stdout='',
stderr='',
rc=0,
start='',
end='',
delta='',
)
startd = datetime.datetime.now()
changed = False
# will return either the image name or None
container_image = is_containerized()
user = "client.admin"
keyring_filename = cluster + '.' + user + '.keyring'
user_key = os.path.join("/etc/ceph/", keyring_filename)
if state == "present":
rc, cmd, out, err = exec_command(module,
check_pool_exist(cluster,
name,
user,
user_key,
container_image=container_image)) # noqa: E501
if rc == 0:
running_pool_details = get_pool_details(module,
cluster,
name,
user,
user_key,
container_image=container_image) # noqa: E501
user_pool_config['pg_placement_num'] = {'value': str(running_pool_details[2]['pg_placement_num']), 'cli_set_opt': 'pgp_num'} # noqa: E501
delta = compare_pool_config(user_pool_config,
running_pool_details[2])
if len(delta) > 0:
keys = list(delta.keys())
details = running_pool_details[2]
if details['erasure_code_profile'] and 'size' in keys:
del delta['size']
if details['pg_autoscale_mode'] == 'on':
delta.pop('pg_num', None)
delta.pop('pgp_num', None)
if len(delta) == 0:
out = "Skipping pool {}.\nUpdating either 'size' on an erasure-coded pool or 'pg_num'/'pgp_num' on a pg autoscaled pool is incompatible".format(name) # noqa: E501
else:
rc, cmd, out, err = update_pool(module,
cluster,
name,
user,
user_key,
delta,
container_image=container_image) # noqa: E501
if rc == 0:
changed = True
else:
out = "Pool {} already exists and there is nothing to update.".format(name) # noqa: E501
else:
rc, cmd, out, err = exec_command(module,
create_pool(cluster,
user,
user_key,
user_pool_config=user_pool_config, # noqa: E501
container_image=container_image)) # noqa: E501
if user_pool_config['application']['value']:
rc, _, _, _ = exec_command(module,
enable_application_pool(cluster,
name,
user_pool_config['application']['value'], # noqa: E501
user,
user_key,
container_image=container_image)) # noqa: E501
if rc == 0 and user_pool_config['application']['value'] == 'rbd': # noqa: E501
rc, cmd, out, err = exec_command(module,
init_rbd_pool(cluster,
user_pool_config['pool_name']['value'], # noqa: E501
user,
user_key,
container_image=container_image)) # noqa: E501
if user_pool_config['min_size']['value']:
# not implemented yet
pass
changed = True
elif state == "list":
rc, cmd, out, err = exec_command(module,
list_pools(cluster,
name, user,
user_key,
details,
container_image=container_image)) # noqa: E501
if rc != 0:
out = "Couldn't list pool(s) present on the cluster"
elif state == "absent":
rc, cmd, out, err = exec_command(module,
check_pool_exist(cluster,
name, user,
user_key,
container_image=container_image)) # noqa: E501
if rc == 0:
rc, cmd, out, err = exec_command(module,
remove_pool(cluster,
name,
user,
user_key,
container_image=container_image)) # noqa: E501
changed = True
else:
rc = 0
out = "Skipped, since pool {} doesn't exist".format(name)
exit_module(module=module, out=out, rc=rc, cmd=cmd, err=err, startd=startd,
changed=changed)
def main():
run_module()
if __name__ == '__main__':
main()
| asm0deuz | e5ad1953dccf7463507b932b04a00a17f3c8d81e | c39bbc3deaf7a02d36daa39d752e91e94afb3c3e | ```suggestion
cmd = generate_cmd(cmd='rbd',
``` | guits | 4 |
ceph/ceph-ansible | 7,355 | Initialize rbd pool at pool creation | When creating a RBD pool it needs to be initialized as per documentation[1] Modified (pre_)generate_ceph_cmd to make it usable with rbd command as well
[1]https://docs.ceph.com/en/latest/rbd/rados-rbd-cmds/#create-a-block-device-pool
Signed-off-by: Teoman ONAY <tonay@redhat.com> | null | 2022-12-02 09:11:22+00:00 | 2023-01-18 13:13:04+00:00 | module_utils/ca_common.py | import os
import datetime
def generate_ceph_cmd(sub_cmd, args, user_key=None, cluster='ceph', user='client.admin', container_image=None, interactive=False):
'''
Generate 'ceph' command line to execute
'''
if not user_key:
user_key = '/etc/ceph/{}.{}.keyring'.format(cluster, user)
cmd = pre_generate_ceph_cmd(container_image=container_image, interactive=interactive)
base_cmd = [
'-n',
user,
'-k',
user_key,
'--cluster',
cluster
]
base_cmd.extend(sub_cmd)
cmd.extend(base_cmd + args)
return cmd
def container_exec(binary, container_image, interactive=False):
'''
Build the docker CLI to run a command inside a container
'''
container_binary = os.getenv('CEPH_CONTAINER_BINARY')
command_exec = [container_binary, 'run']
if interactive:
command_exec.extend(['--interactive'])
command_exec.extend(['--rm',
'--net=host',
'-v', '/etc/ceph:/etc/ceph:z',
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=' + binary, container_image])
return command_exec
def is_containerized():
'''
Check if we are running on a containerized cluster
'''
if 'CEPH_CONTAINER_IMAGE' in os.environ:
container_image = os.getenv('CEPH_CONTAINER_IMAGE')
else:
container_image = None
return container_image
def pre_generate_ceph_cmd(container_image=None, interactive=False):
'''
Generate ceph prefix comaand
'''
if container_image:
cmd = container_exec('ceph', container_image, interactive=interactive)
else:
cmd = ['ceph']
return cmd
def exec_command(module, cmd, stdin=None):
'''
Execute command(s)
'''
binary_data = False
if stdin:
binary_data = True
rc, out, err = module.run_command(cmd, data=stdin, binary_data=binary_data)
return rc, cmd, out, err
def exit_module(module, out, rc, cmd, err, startd, changed=False, diff=dict(before="", after="")):
endd = datetime.datetime.now()
delta = endd - startd
result = dict(
cmd=cmd,
start=str(startd),
end=str(endd),
delta=str(delta),
rc=rc,
stdout=out.rstrip("\r\n"),
stderr=err.rstrip("\r\n"),
changed=changed,
diff=diff
)
module.exit_json(**result)
def fatal(message, module):
'''
Report a fatal error and exit
'''
if module:
module.fail_json(msg=message, rc=1)
else:
raise Exception(message)
| import os
import datetime
def generate_cmd(cmd='ceph',
sub_cmd=None,
args=None,
user_key=None,
cluster='ceph',
user='client.admin',
container_image=None,
interactive=False):
'''
Generate 'ceph' command line to execute
'''
if user_key is None:
user_key = '/etc/ceph/{}.{}.keyring'.format(cluster, user)
cmd = pre_generate_cmd(cmd, container_image=container_image, interactive=interactive) # noqa: E501
base_cmd = [
'-n',
user,
'-k',
user_key,
'--cluster',
cluster
]
if sub_cmd is not None:
base_cmd.extend(sub_cmd)
cmd.extend(base_cmd) if args is None else cmd.extend(base_cmd + args)
return cmd
def container_exec(binary, container_image, interactive=False):
'''
Build the docker CLI to run a command inside a container
'''
container_binary = os.getenv('CEPH_CONTAINER_BINARY')
command_exec = [container_binary, 'run']
if interactive:
command_exec.extend(['--interactive'])
command_exec.extend(['--rm',
'--net=host',
'-v', '/etc/ceph:/etc/ceph:z',
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=' + binary, container_image])
return command_exec
def is_containerized():
'''
Check if we are running on a containerized cluster
'''
if 'CEPH_CONTAINER_IMAGE' in os.environ:
container_image = os.getenv('CEPH_CONTAINER_IMAGE')
else:
container_image = None
return container_image
def pre_generate_cmd(cmd, container_image=None, interactive=False):
'''
Generate ceph prefix command
'''
if container_image:
cmd = container_exec(cmd, container_image, interactive=interactive)
else:
cmd = [cmd]
return cmd
def exec_command(module, cmd, stdin=None):
'''
Execute command(s)
'''
binary_data = False
if stdin:
binary_data = True
rc, out, err = module.run_command(cmd, data=stdin, binary_data=binary_data)
return rc, cmd, out, err
def exit_module(module, out, rc, cmd, err, startd, changed=False, diff=dict(before="", after="")): # noqa: E501
endd = datetime.datetime.now()
delta = endd - startd
result = dict(
cmd=cmd,
start=str(startd),
end=str(endd),
delta=str(delta),
rc=rc,
stdout=out.rstrip("\r\n"),
stderr=err.rstrip("\r\n"),
changed=changed,
diff=diff
)
module.exit_json(**result)
def fatal(message, module):
'''
Report a fatal error and exit
'''
if module:
module.fail_json(msg=message, rc=1)
else:
raise Exception(message)
| asm0deuz | e5ad1953dccf7463507b932b04a00a17f3c8d81e | c39bbc3deaf7a02d36daa39d752e91e94afb3c3e | ```suggestion
def generate_cmd(cmd, sub_cmd, args, user_key=None, cluster='ceph', user='client.admin', container_image=None, interactive=False): # noqa: E501
```
(even though it would be nice to add type annotation...) | guits | 5 |
ceph/ceph-ansible | 7,355 | Initialize rbd pool at pool creation | When creating a RBD pool it needs to be initialized as per documentation[1] Modified (pre_)generate_ceph_cmd to make it usable with rbd command as well
[1]https://docs.ceph.com/en/latest/rbd/rados-rbd-cmds/#create-a-block-device-pool
Signed-off-by: Teoman ONAY <tonay@redhat.com> | null | 2022-12-02 09:11:22+00:00 | 2023-01-18 13:13:04+00:00 | module_utils/ca_common.py | import os
import datetime
def generate_ceph_cmd(sub_cmd, args, user_key=None, cluster='ceph', user='client.admin', container_image=None, interactive=False):
'''
Generate 'ceph' command line to execute
'''
if not user_key:
user_key = '/etc/ceph/{}.{}.keyring'.format(cluster, user)
cmd = pre_generate_ceph_cmd(container_image=container_image, interactive=interactive)
base_cmd = [
'-n',
user,
'-k',
user_key,
'--cluster',
cluster
]
base_cmd.extend(sub_cmd)
cmd.extend(base_cmd + args)
return cmd
def container_exec(binary, container_image, interactive=False):
'''
Build the docker CLI to run a command inside a container
'''
container_binary = os.getenv('CEPH_CONTAINER_BINARY')
command_exec = [container_binary, 'run']
if interactive:
command_exec.extend(['--interactive'])
command_exec.extend(['--rm',
'--net=host',
'-v', '/etc/ceph:/etc/ceph:z',
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=' + binary, container_image])
return command_exec
def is_containerized():
'''
Check if we are running on a containerized cluster
'''
if 'CEPH_CONTAINER_IMAGE' in os.environ:
container_image = os.getenv('CEPH_CONTAINER_IMAGE')
else:
container_image = None
return container_image
def pre_generate_ceph_cmd(container_image=None, interactive=False):
'''
Generate ceph prefix comaand
'''
if container_image:
cmd = container_exec('ceph', container_image, interactive=interactive)
else:
cmd = ['ceph']
return cmd
def exec_command(module, cmd, stdin=None):
'''
Execute command(s)
'''
binary_data = False
if stdin:
binary_data = True
rc, out, err = module.run_command(cmd, data=stdin, binary_data=binary_data)
return rc, cmd, out, err
def exit_module(module, out, rc, cmd, err, startd, changed=False, diff=dict(before="", after="")):
endd = datetime.datetime.now()
delta = endd - startd
result = dict(
cmd=cmd,
start=str(startd),
end=str(endd),
delta=str(delta),
rc=rc,
stdout=out.rstrip("\r\n"),
stderr=err.rstrip("\r\n"),
changed=changed,
diff=diff
)
module.exit_json(**result)
def fatal(message, module):
'''
Report a fatal error and exit
'''
if module:
module.fail_json(msg=message, rc=1)
else:
raise Exception(message)
| import os
import datetime
def generate_cmd(cmd='ceph',
sub_cmd=None,
args=None,
user_key=None,
cluster='ceph',
user='client.admin',
container_image=None,
interactive=False):
'''
Generate 'ceph' command line to execute
'''
if user_key is None:
user_key = '/etc/ceph/{}.{}.keyring'.format(cluster, user)
cmd = pre_generate_cmd(cmd, container_image=container_image, interactive=interactive) # noqa: E501
base_cmd = [
'-n',
user,
'-k',
user_key,
'--cluster',
cluster
]
if sub_cmd is not None:
base_cmd.extend(sub_cmd)
cmd.extend(base_cmd) if args is None else cmd.extend(base_cmd + args)
return cmd
def container_exec(binary, container_image, interactive=False):
'''
Build the docker CLI to run a command inside a container
'''
container_binary = os.getenv('CEPH_CONTAINER_BINARY')
command_exec = [container_binary, 'run']
if interactive:
command_exec.extend(['--interactive'])
command_exec.extend(['--rm',
'--net=host',
'-v', '/etc/ceph:/etc/ceph:z',
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=' + binary, container_image])
return command_exec
def is_containerized():
'''
Check if we are running on a containerized cluster
'''
if 'CEPH_CONTAINER_IMAGE' in os.environ:
container_image = os.getenv('CEPH_CONTAINER_IMAGE')
else:
container_image = None
return container_image
def pre_generate_cmd(cmd, container_image=None, interactive=False):
'''
Generate ceph prefix command
'''
if container_image:
cmd = container_exec(cmd, container_image, interactive=interactive)
else:
cmd = [cmd]
return cmd
def exec_command(module, cmd, stdin=None):
'''
Execute command(s)
'''
binary_data = False
if stdin:
binary_data = True
rc, out, err = module.run_command(cmd, data=stdin, binary_data=binary_data)
return rc, cmd, out, err
def exit_module(module, out, rc, cmd, err, startd, changed=False, diff=dict(before="", after="")): # noqa: E501
endd = datetime.datetime.now()
delta = endd - startd
result = dict(
cmd=cmd,
start=str(startd),
end=str(endd),
delta=str(delta),
rc=rc,
stdout=out.rstrip("\r\n"),
stderr=err.rstrip("\r\n"),
changed=changed,
diff=diff
)
module.exit_json(**result)
def fatal(message, module):
'''
Report a fatal error and exit
'''
if module:
module.fail_json(msg=message, rc=1)
else:
raise Exception(message)
| asm0deuz | e5ad1953dccf7463507b932b04a00a17f3c8d81e | c39bbc3deaf7a02d36daa39d752e91e94afb3c3e | ```suggestion
def generate_cmd(cmd = 'ceph',
sub_cmd = None,
args = None,
user_key = None,
cluster = 'ceph',
user = 'client.admin',
container_image = None,
interactive = False):
``` | guits | 6 |
ceph/ceph-ansible | 7,355 | Initialize rbd pool at pool creation | When creating a RBD pool it needs to be initialized as per documentation[1] Modified (pre_)generate_ceph_cmd to make it usable with rbd command as well
[1]https://docs.ceph.com/en/latest/rbd/rados-rbd-cmds/#create-a-block-device-pool
Signed-off-by: Teoman ONAY <tonay@redhat.com> | null | 2022-12-02 09:11:22+00:00 | 2023-01-18 13:13:04+00:00 | module_utils/ca_common.py | import os
import datetime
def generate_ceph_cmd(sub_cmd, args, user_key=None, cluster='ceph', user='client.admin', container_image=None, interactive=False):
'''
Generate 'ceph' command line to execute
'''
if not user_key:
user_key = '/etc/ceph/{}.{}.keyring'.format(cluster, user)
cmd = pre_generate_ceph_cmd(container_image=container_image, interactive=interactive)
base_cmd = [
'-n',
user,
'-k',
user_key,
'--cluster',
cluster
]
base_cmd.extend(sub_cmd)
cmd.extend(base_cmd + args)
return cmd
def container_exec(binary, container_image, interactive=False):
'''
Build the docker CLI to run a command inside a container
'''
container_binary = os.getenv('CEPH_CONTAINER_BINARY')
command_exec = [container_binary, 'run']
if interactive:
command_exec.extend(['--interactive'])
command_exec.extend(['--rm',
'--net=host',
'-v', '/etc/ceph:/etc/ceph:z',
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=' + binary, container_image])
return command_exec
def is_containerized():
'''
Check if we are running on a containerized cluster
'''
if 'CEPH_CONTAINER_IMAGE' in os.environ:
container_image = os.getenv('CEPH_CONTAINER_IMAGE')
else:
container_image = None
return container_image
def pre_generate_ceph_cmd(container_image=None, interactive=False):
'''
Generate ceph prefix comaand
'''
if container_image:
cmd = container_exec('ceph', container_image, interactive=interactive)
else:
cmd = ['ceph']
return cmd
def exec_command(module, cmd, stdin=None):
'''
Execute command(s)
'''
binary_data = False
if stdin:
binary_data = True
rc, out, err = module.run_command(cmd, data=stdin, binary_data=binary_data)
return rc, cmd, out, err
def exit_module(module, out, rc, cmd, err, startd, changed=False, diff=dict(before="", after="")):
endd = datetime.datetime.now()
delta = endd - startd
result = dict(
cmd=cmd,
start=str(startd),
end=str(endd),
delta=str(delta),
rc=rc,
stdout=out.rstrip("\r\n"),
stderr=err.rstrip("\r\n"),
changed=changed,
diff=diff
)
module.exit_json(**result)
def fatal(message, module):
'''
Report a fatal error and exit
'''
if module:
module.fail_json(msg=message, rc=1)
else:
raise Exception(message)
| import os
import datetime
def generate_cmd(cmd='ceph',
sub_cmd=None,
args=None,
user_key=None,
cluster='ceph',
user='client.admin',
container_image=None,
interactive=False):
'''
Generate 'ceph' command line to execute
'''
if user_key is None:
user_key = '/etc/ceph/{}.{}.keyring'.format(cluster, user)
cmd = pre_generate_cmd(cmd, container_image=container_image, interactive=interactive) # noqa: E501
base_cmd = [
'-n',
user,
'-k',
user_key,
'--cluster',
cluster
]
if sub_cmd is not None:
base_cmd.extend(sub_cmd)
cmd.extend(base_cmd) if args is None else cmd.extend(base_cmd + args)
return cmd
def container_exec(binary, container_image, interactive=False):
'''
Build the docker CLI to run a command inside a container
'''
container_binary = os.getenv('CEPH_CONTAINER_BINARY')
command_exec = [container_binary, 'run']
if interactive:
command_exec.extend(['--interactive'])
command_exec.extend(['--rm',
'--net=host',
'-v', '/etc/ceph:/etc/ceph:z',
'-v', '/var/lib/ceph/:/var/lib/ceph/:z',
'-v', '/var/log/ceph/:/var/log/ceph/:z',
'--entrypoint=' + binary, container_image])
return command_exec
def is_containerized():
'''
Check if we are running on a containerized cluster
'''
if 'CEPH_CONTAINER_IMAGE' in os.environ:
container_image = os.getenv('CEPH_CONTAINER_IMAGE')
else:
container_image = None
return container_image
def pre_generate_cmd(cmd, container_image=None, interactive=False):
'''
Generate ceph prefix command
'''
if container_image:
cmd = container_exec(cmd, container_image, interactive=interactive)
else:
cmd = [cmd]
return cmd
def exec_command(module, cmd, stdin=None):
'''
Execute command(s)
'''
binary_data = False
if stdin:
binary_data = True
rc, out, err = module.run_command(cmd, data=stdin, binary_data=binary_data)
return rc, cmd, out, err
def exit_module(module, out, rc, cmd, err, startd, changed=False, diff=dict(before="", after="")): # noqa: E501
endd = datetime.datetime.now()
delta = endd - startd
result = dict(
cmd=cmd,
start=str(startd),
end=str(endd),
delta=str(delta),
rc=rc,
stdout=out.rstrip("\r\n"),
stderr=err.rstrip("\r\n"),
changed=changed,
diff=diff
)
module.exit_json(**result)
def fatal(message, module):
'''
Report a fatal error and exit
'''
if module:
module.fail_json(msg=message, rc=1)
else:
raise Exception(message)
| asm0deuz | e5ad1953dccf7463507b932b04a00a17f3c8d81e | c39bbc3deaf7a02d36daa39d752e91e94afb3c3e | ```suggestion
cmd = pre_generate_cmd([cmd], container_image=container_image, interactive=interactive) # noqa: E501
``` | guits | 7 |
ceph/ceph-ansible | 7,326 | common: stop using ceph/daemon entrypoint | major refactor in order to make ceph-ansible use the `ceph/ceph` container image instead of `ceph/daemon` | null | 2022-10-07 12:52:53+00:00 | 2023-05-31 21:07:13+00:00 | roles/ceph-mon/templates/ceph-mon.service.j2 | [Unit]
Description=Ceph Monitor
PartOf=ceph-mon.target
{% if container_binary == 'docker' %}
After=docker.service network-online.target local-fs.target time-sync.target
Requires=docker.service
{% else %}
After=network-online.target local-fs.target time-sync.target
{% endif %}
Wants=network-online.target local-fs.target time-sync.target
[Service]
EnvironmentFile=-/etc/environment
{% if container_binary == 'podman' %}
ExecStartPre=-/usr/bin/rm -f /%t/%n-pid /%t/%n-cid
ExecStartPre=-/usr/bin/{{ container_binary }} rm --storage ceph-mon-%i
ExecStartPre=-/usr/bin/mkdir -p /var/log/ceph
{% else %}
ExecStartPre=-/usr/bin/{{ container_binary }} stop ceph-mon-%i
{% endif %}
ExecStartPre=-/usr/bin/{{ container_binary }} rm ceph-mon-%i
ExecStartPre=/bin/sh -c '"$(command -v mkdir)" -p /etc/ceph /var/lib/ceph/mon'
ExecStart=/usr/bin/{{ container_binary }} run --rm --name ceph-mon-%i \
{% if container_binary == 'podman' %}
-d --log-driver journald --conmon-pidfile /%t/%n-pid --cidfile /%t/%n-cid \
{% endif %}
--pids-limit={{ 0 if container_binary == 'podman' else -1 }} \
--memory={{ ceph_mon_docker_memory_limit }} \
--cpus={{ ceph_mon_docker_cpu_limit }} \
--security-opt label=disable \
-v /var/lib/ceph/mon:/var/lib/ceph/mon:z,rshared \
-v /etc/ceph:/etc/ceph:z \
-v /var/run/ceph:/var/run/ceph:z \
-v /etc/localtime:/etc/localtime:ro \
-v /var/log/ceph:/var/log/ceph:z \
{% if ansible_facts['os_family'] == 'RedHat' -%}
-v /etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted \
{% endif -%}
{% if mon_docker_privileged | bool -%}
--privileged \
{% endif -%}
{% if mon_docker_net_host | bool -%}
--net=host \
{% endif -%}
-e IP_VERSION={{ ip_version[-1:] }} \
-e MON_IP={{ _current_monitor_address }} \
-e CLUSTER={{ cluster }} \
-e FSID={{ fsid }} \
-e MON_PORT={{ ceph_mon_container_listen_port }} \
-e CEPH_PUBLIC_NETWORK={{ public_network | regex_replace(' ', '') }} \
-e CONTAINER_IMAGE={{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
-e TCMALLOC_MAX_TOTAL_THREAD_CACHE_BYTES={{ ceph_tcmalloc_max_total_thread_cache }} \
{{ ceph_mon_docker_extra_env }} \
--entrypoint=/usr/bin/ceph-mon \
{{ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
-f --default-log-to-file=false --default-log-to-stderr=true \
-i {{ monitor_name }} --mon-data /var/lib/ceph/mon/{{ cluster }}-{{ monitor_name }} --public-addr {{ _current_monitor_address }}
{% if container_binary == 'podman' %}
ExecStop=-/usr/bin/sh -c "/usr/bin/{{ container_binary }} rm -f `cat /%t/%n-cid`"
{% else %}
ExecStop=-/usr/bin/{{ container_binary }} stop ceph-mon-%i
{% endif %}
ExecStopPost=-/bin/rm -f /var/run/ceph/{{ cluster }}-mon.{{ monitor_name }}.asok
KillMode=none
Restart=always
RestartSec=10s
TimeoutStartSec=120
TimeoutStopSec=15
{% if container_binary == 'podman' %}
Type=forking
PIDFile=/%t/%n-pid
{% endif %}
[Install]
WantedBy=ceph.target
| [Unit]
Description=Ceph Monitor
PartOf=ceph-mon.target
{% if container_binary == 'docker' %}
After=docker.service network-online.target local-fs.target time-sync.target
Requires=docker.service
{% else %}
After=network-online.target local-fs.target time-sync.target
{% endif %}
Wants=network-online.target local-fs.target time-sync.target
[Service]
EnvironmentFile=-/etc/environment
{% if container_binary == 'podman' %}
ExecStartPre=-/usr/bin/rm -f /%t/%n-pid /%t/%n-cid
ExecStartPre=-/usr/bin/{{ container_binary }} rm --storage ceph-mon-%i
ExecStartPre=-/usr/bin/mkdir -p /var/log/ceph
{% else %}
ExecStartPre=-/usr/bin/{{ container_binary }} stop ceph-mon-%i
{% endif %}
ExecStartPre=-/usr/bin/{{ container_binary }} rm ceph-mon-%i
ExecStartPre=/bin/sh -c '"$(command -v mkdir)" -p /etc/ceph /var/lib/ceph/mon'
ExecStart=/usr/bin/{{ container_binary }} run --rm --name ceph-mon-%i \
{% if container_binary == 'podman' %}
-d --log-driver journald --conmon-pidfile /%t/%n-pid --cidfile /%t/%n-cid \
{% endif %}
--pids-limit={{ 0 if container_binary == 'podman' else -1 }} \
--memory={{ ceph_mon_docker_memory_limit }} \
--cpus={{ ceph_mon_docker_cpu_limit }} \
--security-opt label=disable \
-v /var/lib/ceph/mon:/var/lib/ceph/mon:z,rshared \
-v /etc/ceph:/etc/ceph:z \
-v /var/run/ceph:/var/run/ceph:z \
-v /etc/localtime:/etc/localtime:ro \
-v /var/log/ceph:/var/log/ceph:z \
{% if ansible_facts['os_family'] == 'RedHat' -%}
-v /etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted \
{% endif -%}
{% if mon_docker_privileged | bool -%}
--privileged \
{% endif -%}
{% if mon_docker_net_host | bool -%}
--net=host \
{% endif -%}
-e IP_VERSION={{ ip_version[-1:] }} \
-e MON_IP={{ _current_monitor_address }} \
-e CLUSTER={{ cluster }} \
-e FSID={{ fsid }} \
-e MON_PORT={{ ceph_mon_container_listen_port }} \
-e CEPH_PUBLIC_NETWORK={{ public_network | regex_replace(' ', '') }} \
-e CONTAINER_IMAGE={{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
-e TCMALLOC_MAX_TOTAL_THREAD_CACHE_BYTES={{ ceph_tcmalloc_max_total_thread_cache }} \
{{ ceph_mon_docker_extra_env }} \
--entrypoint=/usr/bin/ceph-mon \
{{ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
-f --default-log-to-file=false --default-log-to-stderr=true \
-i {{ monitor_name }} --mon-data /var/lib/ceph/mon/{{ cluster }}-{{ monitor_name }} --public-addr {{ _current_monitor_address }}
{% if container_binary == 'podman' %}
ExecStop=-/usr/bin/sh -c "/usr/bin/{{ container_binary }} rm -f `cat /%t/%n-cid`"
{% else %}
ExecStop=-/usr/bin/{{ container_binary }} stop ceph-mon-%i
{% endif %}
ExecStopPost=-/bin/rm -f /var/run/ceph/{{ cluster }}-mon.{{ monitor_name }}.asok
KillMode=none
Restart=always
RestartSec=10s
TimeoutStartSec=120
TimeoutStopSec=15
{% if container_binary == 'podman' %}
Type=forking
PIDFile=/%t/%n-pid
{% endif %}
[Install]
WantedBy=ceph.target
| guits | 5cd692dcdc8dd55036b8c283f1bca56f79965c1d | 23a8bbc6c59d78e982f343c06cfb5fe8e86cb757 | ```suggestion
-i {{ monitor_name }} --mon-data /var/lib/ceph/mon/{{ cluster }}-{{ monitor_name }} --public-addr {{ _current_monitor_address }}
``` | guits | 8 |
ceph/ceph-ansible | 7,326 | common: stop using ceph/daemon entrypoint | major refactor in order to make ceph-ansible use the `ceph/ceph` container image instead of `ceph/daemon` | null | 2022-10-07 12:52:53+00:00 | 2023-05-31 21:07:13+00:00 | roles/ceph-nfs/tasks/pre_requisite_container.yml | ---
- name: keyring related tasks
when: groups.get(mon_group_name, []) | length > 0
block:
- name: set_fact container_exec_cmd
set_fact:
container_exec_cmd: "{{ container_binary }} exec ceph-mon-{{ hostvars[item]['ansible_facts']['hostname'] }}"
with_items: "{{ groups.get(mon_group_name, []) }}"
delegate_to: "{{ item }}"
delegate_facts: true
run_once: true
- name: "/var/lib/ceph/radosgw/{{ cluster }}-{{ ansible_facts['hostname'] }}"
file:
path: "{{ item.0 }}"
state: "directory"
owner: "{{ ceph_uid }}"
group: "{{ ceph_uid }}"
mode: "0755"
delegate_to: "{{ item.1 }}"
with_nested:
- ["/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}",
"/var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}" ]
- [ "{{ groups.get(mon_group_name)[0] }}", "{{ inventory_hostname }}" ]
- name: set_fact keyrings_list
set_fact:
keyrings_list:
- { name: "client.bootstrap-rgw", path: "/var/lib/ceph/bootstrap-rgw/{{ cluster }}.keyring", copy_key: "{{ nfs_obj_gw }}" }
- { name: "client.admin", path: "/etc/ceph/{{ cluster }}.client.admin.keyring", copy_key: "{{ copy_admin_key }}" }
- { name: "client.rgw.{{ ansible_facts['hostname'] }}", create: True, path: "/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring", caps: { "mon": "allow r", "osd": "allow rwx tag rgw *=*"} }
- { name: "client.nfs.{{ ansible_facts['hostname'] }}", create: True, path: "/var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}/keyring", caps: { "mon": "r", "osd": "allow rw pool=.nfs"} }
- name: create keyrings from a monitor
ceph_key:
name: "{{ item.name }}"
cluster: "{{ cluster }}"
dest: "{{ item.path }}"
caps: "{{ item.caps }}"
import_key: True
owner: "{{ ceph_uid }}"
group: "{{ ceph_uid }}"
mode: "0600"
no_log: "{{ no_log_on_ceph_key_tasks }}"
environment:
CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment else None }}"
CEPH_CONTAINER_BINARY: "{{ container_binary }}"
delegate_to: "{{ groups.get(mon_group_name)[0] }}"
loop: "{{ keyrings_list }}"
when:
- cephx | bool
- item.create | default(False) | bool
- name: get keys from monitors
ceph_key:
name: "{{ item.name }}"
cluster: "{{ cluster }}"
output_format: plain
state: info
environment:
CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment | bool else None }}"
CEPH_CONTAINER_BINARY: "{{ container_binary }}"
register: _rgw_keys
loop: "{{ keyrings_list }}"
delegate_to: "{{ groups.get(mon_group_name)[0] }}"
run_once: true
when:
- cephx | bool
- item.copy_key | default(True) | bool
no_log: "{{ no_log_on_ceph_key_tasks }}"
- name: debug
debug:
msg: "{{ _rgw_keys }}"
- name: copy ceph key(s) if needed
copy:
dest: "{{ item.item.path }}"
content: "{{ item.stdout + '\n' }}"
owner: "{{ ceph_uid if containerized_deployment | bool else 'ceph' }}"
group: "{{ ceph_uid if containerized_deployment | bool else 'ceph' }}"
mode: "{{ ceph_keyring_permissions }}"
with_items: "{{ _rgw_keys.results }}"
when:
- cephx | bool
- item.item.copy_key | default(True) | bool
no_log: "{{ no_log_on_ceph_key_tasks }}"
- name: dbus related tasks
block:
- name: get file
command: "{{ container_binary }} run --rm --entrypoint=cat {{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag }} /etc/dbus-1/system.d/org.ganesha.nfsd.conf"
register: dbus_ganesha_file
run_once: true
changed_when: false
- name: create dbus service file
copy:
content: "{{ dbus_ganesha_file.stdout }}"
dest: /etc/dbus-1/system.d/org.ganesha.nfsd.conf
owner: "root"
group: "root"
mode: "0644"
- name: reload dbus configuration
command: "killall -SIGHUP dbus-daemon"
when: ceph_nfs_dynamic_exports | bool
| ---
- name: keyring related tasks
when: groups.get(mon_group_name, []) | length > 0
block:
- name: set_fact container_exec_cmd
set_fact:
container_exec_cmd: "{{ container_binary }} exec ceph-mon-{{ hostvars[item]['ansible_facts']['hostname'] }}"
with_items: "{{ groups.get(mon_group_name, []) }}"
delegate_to: "{{ item }}"
delegate_facts: true
run_once: true
- name: "/var/lib/ceph/radosgw/{{ cluster }}-{{ ansible_facts['hostname'] }}"
file:
path: "{{ item.0 }}"
state: "directory"
owner: "{{ ceph_uid }}"
group: "{{ ceph_uid }}"
mode: "0755"
delegate_to: "{{ item.1 }}"
with_nested:
- ["/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}",
"/var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}" ]
- [ "{{ groups.get(mon_group_name)[0] }}", "{{ inventory_hostname }}" ]
- name: set_fact keyrings_list
set_fact:
keyrings_list:
- { name: "client.bootstrap-rgw", path: "/var/lib/ceph/bootstrap-rgw/{{ cluster }}.keyring", copy_key: "{{ nfs_obj_gw }}" }
- { name: "client.admin", path: "/etc/ceph/{{ cluster }}.client.admin.keyring", copy_key: "{{ copy_admin_key }}" }
- { name: "client.rgw.{{ ansible_facts['hostname'] }}", create: True, path: "/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring", caps: { "mon": "allow r", "osd": "allow rwx tag rgw *=*"} }
- { name: "client.nfs.{{ ansible_facts['hostname'] }}", create: True, path: "/var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}/keyring", caps: { "mon": "r", "osd": "allow rw pool=.nfs"} }
- name: create keyrings from a monitor
ceph_key:
name: "{{ item.name }}"
cluster: "{{ cluster }}"
dest: "{{ item.path }}"
caps: "{{ item.caps }}"
import_key: True
owner: "{{ ceph_uid }}"
group: "{{ ceph_uid }}"
mode: "0600"
no_log: "{{ no_log_on_ceph_key_tasks }}"
environment:
CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment else None }}"
CEPH_CONTAINER_BINARY: "{{ container_binary }}"
delegate_to: "{{ groups.get(mon_group_name)[0] }}"
loop: "{{ keyrings_list }}"
when:
- cephx | bool
- item.create | default(False) | bool
- name: get keys from monitors
ceph_key:
name: "{{ item.name }}"
cluster: "{{ cluster }}"
output_format: plain
state: info
environment:
CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment | bool else None }}"
CEPH_CONTAINER_BINARY: "{{ container_binary }}"
register: _rgw_keys
loop: "{{ keyrings_list }}"
delegate_to: "{{ groups.get(mon_group_name)[0] }}"
run_once: true
when:
- cephx | bool
- item.copy_key | default(True) | bool
no_log: "{{ no_log_on_ceph_key_tasks }}"
- name: debug
debug:
msg: "{{ _rgw_keys }}"
- name: copy ceph key(s) if needed
copy:
dest: "{{ item.item.path }}"
content: "{{ item.stdout + '\n' }}"
owner: "{{ ceph_uid if containerized_deployment | bool else 'ceph' }}"
group: "{{ ceph_uid if containerized_deployment | bool else 'ceph' }}"
mode: "{{ ceph_keyring_permissions }}"
with_items: "{{ _rgw_keys.results }}"
when:
- cephx | bool
- item.item.copy_key | default(True) | bool
no_log: "{{ no_log_on_ceph_key_tasks }}"
- name: dbus related tasks
block:
- name: get file
command: "{{ container_binary }} run --rm --entrypoint=cat {{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag }} /etc/dbus-1/system.d/org.ganesha.nfsd.conf"
register: dbus_ganesha_file
run_once: true
changed_when: false
- name: create dbus service file
copy:
content: "{{ dbus_ganesha_file.stdout }}"
dest: /etc/dbus-1/system.d/org.ganesha.nfsd.conf
owner: "root"
group: "root"
mode: "0644"
- name: reload dbus configuration
command: "killall -SIGHUP dbus-daemon"
when: ceph_nfs_dynamic_exports | bool
| guits | 5cd692dcdc8dd55036b8c283f1bca56f79965c1d | 23a8bbc6c59d78e982f343c06cfb5fe8e86cb757 | need to figure out what to do with this | guits | 9 |
ceph/ceph-ansible | 7,326 | common: stop using ceph/daemon entrypoint | major refactor in order to make ceph-ansible use the `ceph/ceph` container image instead of `ceph/daemon` | null | 2022-10-07 12:52:53+00:00 | 2023-05-31 21:07:13+00:00 | roles/ceph-nfs/tasks/pre_requisite_container.yml | ---
- name: keyring related tasks
when: groups.get(mon_group_name, []) | length > 0
block:
- name: set_fact container_exec_cmd
set_fact:
container_exec_cmd: "{{ container_binary }} exec ceph-mon-{{ hostvars[item]['ansible_facts']['hostname'] }}"
with_items: "{{ groups.get(mon_group_name, []) }}"
delegate_to: "{{ item }}"
delegate_facts: true
run_once: true
- name: "/var/lib/ceph/radosgw/{{ cluster }}-{{ ansible_facts['hostname'] }}"
file:
path: "{{ item.0 }}"
state: "directory"
owner: "{{ ceph_uid }}"
group: "{{ ceph_uid }}"
mode: "0755"
delegate_to: "{{ item.1 }}"
with_nested:
- ["/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}",
"/var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}" ]
- [ "{{ groups.get(mon_group_name)[0] }}", "{{ inventory_hostname }}" ]
- name: set_fact keyrings_list
set_fact:
keyrings_list:
- { name: "client.bootstrap-rgw", path: "/var/lib/ceph/bootstrap-rgw/{{ cluster }}.keyring", copy_key: "{{ nfs_obj_gw }}" }
- { name: "client.admin", path: "/etc/ceph/{{ cluster }}.client.admin.keyring", copy_key: "{{ copy_admin_key }}" }
- { name: "client.rgw.{{ ansible_facts['hostname'] }}", create: True, path: "/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring", caps: { "mon": "allow r", "osd": "allow rwx tag rgw *=*"} }
- { name: "client.nfs.{{ ansible_facts['hostname'] }}", create: True, path: "/var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}/keyring", caps: { "mon": "r", "osd": "allow rw pool=.nfs"} }
- name: create keyrings from a monitor
ceph_key:
name: "{{ item.name }}"
cluster: "{{ cluster }}"
dest: "{{ item.path }}"
caps: "{{ item.caps }}"
import_key: True
owner: "{{ ceph_uid }}"
group: "{{ ceph_uid }}"
mode: "0600"
no_log: "{{ no_log_on_ceph_key_tasks }}"
environment:
CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment else None }}"
CEPH_CONTAINER_BINARY: "{{ container_binary }}"
delegate_to: "{{ groups.get(mon_group_name)[0] }}"
loop: "{{ keyrings_list }}"
when:
- cephx | bool
- item.create | default(False) | bool
- name: get keys from monitors
ceph_key:
name: "{{ item.name }}"
cluster: "{{ cluster }}"
output_format: plain
state: info
environment:
CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment | bool else None }}"
CEPH_CONTAINER_BINARY: "{{ container_binary }}"
register: _rgw_keys
loop: "{{ keyrings_list }}"
delegate_to: "{{ groups.get(mon_group_name)[0] }}"
run_once: true
when:
- cephx | bool
- item.copy_key | default(True) | bool
no_log: "{{ no_log_on_ceph_key_tasks }}"
- name: debug
debug:
msg: "{{ _rgw_keys }}"
- name: copy ceph key(s) if needed
copy:
dest: "{{ item.item.path }}"
content: "{{ item.stdout + '\n' }}"
owner: "{{ ceph_uid if containerized_deployment | bool else 'ceph' }}"
group: "{{ ceph_uid if containerized_deployment | bool else 'ceph' }}"
mode: "{{ ceph_keyring_permissions }}"
with_items: "{{ _rgw_keys.results }}"
when:
- cephx | bool
- item.item.copy_key | default(True) | bool
no_log: "{{ no_log_on_ceph_key_tasks }}"
- name: dbus related tasks
block:
- name: get file
command: "{{ container_binary }} run --rm --entrypoint=cat {{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag }} /etc/dbus-1/system.d/org.ganesha.nfsd.conf"
register: dbus_ganesha_file
run_once: true
changed_when: false
- name: create dbus service file
copy:
content: "{{ dbus_ganesha_file.stdout }}"
dest: /etc/dbus-1/system.d/org.ganesha.nfsd.conf
owner: "root"
group: "root"
mode: "0644"
- name: reload dbus configuration
command: "killall -SIGHUP dbus-daemon"
when: ceph_nfs_dynamic_exports | bool
| ---
- name: keyring related tasks
when: groups.get(mon_group_name, []) | length > 0
block:
- name: set_fact container_exec_cmd
set_fact:
container_exec_cmd: "{{ container_binary }} exec ceph-mon-{{ hostvars[item]['ansible_facts']['hostname'] }}"
with_items: "{{ groups.get(mon_group_name, []) }}"
delegate_to: "{{ item }}"
delegate_facts: true
run_once: true
- name: "/var/lib/ceph/radosgw/{{ cluster }}-{{ ansible_facts['hostname'] }}"
file:
path: "{{ item.0 }}"
state: "directory"
owner: "{{ ceph_uid }}"
group: "{{ ceph_uid }}"
mode: "0755"
delegate_to: "{{ item.1 }}"
with_nested:
- ["/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}",
"/var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}" ]
- [ "{{ groups.get(mon_group_name)[0] }}", "{{ inventory_hostname }}" ]
- name: set_fact keyrings_list
set_fact:
keyrings_list:
- { name: "client.bootstrap-rgw", path: "/var/lib/ceph/bootstrap-rgw/{{ cluster }}.keyring", copy_key: "{{ nfs_obj_gw }}" }
- { name: "client.admin", path: "/etc/ceph/{{ cluster }}.client.admin.keyring", copy_key: "{{ copy_admin_key }}" }
- { name: "client.rgw.{{ ansible_facts['hostname'] }}", create: True, path: "/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring", caps: { "mon": "allow r", "osd": "allow rwx tag rgw *=*"} }
- { name: "client.nfs.{{ ansible_facts['hostname'] }}", create: True, path: "/var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}/keyring", caps: { "mon": "r", "osd": "allow rw pool=.nfs"} }
- name: create keyrings from a monitor
ceph_key:
name: "{{ item.name }}"
cluster: "{{ cluster }}"
dest: "{{ item.path }}"
caps: "{{ item.caps }}"
import_key: True
owner: "{{ ceph_uid }}"
group: "{{ ceph_uid }}"
mode: "0600"
no_log: "{{ no_log_on_ceph_key_tasks }}"
environment:
CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment else None }}"
CEPH_CONTAINER_BINARY: "{{ container_binary }}"
delegate_to: "{{ groups.get(mon_group_name)[0] }}"
loop: "{{ keyrings_list }}"
when:
- cephx | bool
- item.create | default(False) | bool
- name: get keys from monitors
ceph_key:
name: "{{ item.name }}"
cluster: "{{ cluster }}"
output_format: plain
state: info
environment:
CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment | bool else None }}"
CEPH_CONTAINER_BINARY: "{{ container_binary }}"
register: _rgw_keys
loop: "{{ keyrings_list }}"
delegate_to: "{{ groups.get(mon_group_name)[0] }}"
run_once: true
when:
- cephx | bool
- item.copy_key | default(True) | bool
no_log: "{{ no_log_on_ceph_key_tasks }}"
- name: debug
debug:
msg: "{{ _rgw_keys }}"
- name: copy ceph key(s) if needed
copy:
dest: "{{ item.item.path }}"
content: "{{ item.stdout + '\n' }}"
owner: "{{ ceph_uid if containerized_deployment | bool else 'ceph' }}"
group: "{{ ceph_uid if containerized_deployment | bool else 'ceph' }}"
mode: "{{ ceph_keyring_permissions }}"
with_items: "{{ _rgw_keys.results }}"
when:
- cephx | bool
- item.item.copy_key | default(True) | bool
no_log: "{{ no_log_on_ceph_key_tasks }}"
- name: dbus related tasks
block:
- name: get file
command: "{{ container_binary }} run --rm --entrypoint=cat {{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag }} /etc/dbus-1/system.d/org.ganesha.nfsd.conf"
register: dbus_ganesha_file
run_once: true
changed_when: false
- name: create dbus service file
copy:
content: "{{ dbus_ganesha_file.stdout }}"
dest: /etc/dbus-1/system.d/org.ganesha.nfsd.conf
owner: "root"
group: "root"
mode: "0644"
- name: reload dbus configuration
command: "killall -SIGHUP dbus-daemon"
when: ceph_nfs_dynamic_exports | bool
| guits | 5cd692dcdc8dd55036b8c283f1bca56f79965c1d | 23a8bbc6c59d78e982f343c06cfb5fe8e86cb757 | this has to be uncommented out | guits | 10 |
ceph/ceph-ansible | 7,326 | common: stop using ceph/daemon entrypoint | major refactor in order to make ceph-ansible use the `ceph/ceph` container image instead of `ceph/daemon` | null | 2022-10-07 12:52:53+00:00 | 2023-05-31 21:07:13+00:00 | roles/ceph-nfs/templates/ceph-nfs.service.j2 | [Unit]
Description=NFS-Ganesha file server
Documentation=http://github.com/nfs-ganesha/nfs-ganesha/wiki
{% if container_binary == 'docker' %}
After=docker.service network-online.target local-fs.target time-sync.target
Requires=docker.service
{% else %}
After=network-online.target local-fs.target time-sync.target
{% endif %}
Wants=network-online.target local-fs.target time-sync.target
[Service]
EnvironmentFile=-/etc/environment
{% if container_binary == 'podman' %}
ExecStartPre=-/usr/bin/rm -f /%t/%n-pid /%t/%n-cid
ExecStartPre=-/usr/bin/{{ container_binary }} rm --storage ceph-nfs-%i
ExecStartPre=-/usr/bin/mkdir -p /var/log/ceph /var/log/ganesha
{% endif %}
ExecStartPre=-/usr/bin/{{ container_binary }} rm ceph-nfs-%i
ExecStartPre={{ '/bin/mkdir' if ansible_facts['os_family'] == 'Debian' else '/usr/bin/mkdir' }} -p /etc/ceph /etc/ganesha /var/lib/nfs/ganesha /var/log/ganesha
ExecStart=/usr/bin/{{ container_binary }} run --rm --net=host \
{% if container_binary == 'podman' %}
-d --log-driver journald --conmon-pidfile /%t/%n-pid --cidfile /%t/%n-cid \
{% endif %}
--pids-limit={{ 0 if container_binary == 'podman' else -1 }} \
-v /etc/ceph:/etc/ceph:z \
-v /var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring:/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring:z \
-v /var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}/keyring:/etc/ceph/keyring:z \
-v /etc/ganesha:/etc/ganesha:z \
-v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket \
-v /var/run/ceph:/var/run/ceph:z \
-v /var/log/ceph:/var/log/ceph:z \
-v /var/log/ganesha:/var/log/ganesha:z \
-v /etc/localtime:/etc/localtime:ro \
{{ ceph_nfs_docker_extra_env }} \
--entrypoint=/usr/bin/ganesha.nfsd \
--name=ceph-nfs-{{ ceph_nfs_service_suffix | default(ansible_facts['hostname']) }} \
{{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
-F -L STDOUT
{% if container_binary == 'podman' %}
ExecStop=-/usr/bin/sh -c "/usr/bin/{{ container_binary }} rm -f `cat /%t/%n-cid`"
{% else %}
ExecStopPost=-/usr/bin/{{ container_binary }} stop ceph-nfs-%i
{% endif %}
KillMode=none
Restart=always
RestartSec=10s
TimeoutStartSec=120
TimeoutStopSec=15
{% if container_binary == 'podman' %}
Type=forking
PIDFile=/%t/%n-pid
{% endif %}
[Install]
WantedBy=multi-user.target
| [Unit]
Description=NFS-Ganesha file server
Documentation=http://github.com/nfs-ganesha/nfs-ganesha/wiki
{% if container_binary == 'docker' %}
After=docker.service network-online.target local-fs.target time-sync.target
Requires=docker.service
{% else %}
After=network-online.target local-fs.target time-sync.target
{% endif %}
Wants=network-online.target local-fs.target time-sync.target
[Service]
EnvironmentFile=-/etc/environment
{% if container_binary == 'podman' %}
ExecStartPre=-/usr/bin/rm -f /%t/%n-pid /%t/%n-cid
ExecStartPre=-/usr/bin/{{ container_binary }} rm --storage ceph-nfs-%i
ExecStartPre=-/usr/bin/mkdir -p /var/log/ceph /var/log/ganesha
{% endif %}
ExecStartPre=-/usr/bin/{{ container_binary }} rm ceph-nfs-%i
ExecStartPre={{ '/bin/mkdir' if ansible_facts['os_family'] == 'Debian' else '/usr/bin/mkdir' }} -p /etc/ceph /etc/ganesha /var/lib/nfs/ganesha /var/log/ganesha
ExecStart=/usr/bin/{{ container_binary }} run --rm --net=host \
{% if container_binary == 'podman' %}
-d --log-driver journald --conmon-pidfile /%t/%n-pid --cidfile /%t/%n-cid \
{% endif %}
--pids-limit={{ 0 if container_binary == 'podman' else -1 }} \
-v /etc/ceph:/etc/ceph:z \
-v /var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring:/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring:z \
-v /var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}/keyring:/etc/ceph/keyring:z \
-v /etc/ganesha:/etc/ganesha:z \
-v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket \
-v /var/run/ceph:/var/run/ceph:z \
-v /var/log/ceph:/var/log/ceph:z \
-v /var/log/ganesha:/var/log/ganesha:z \
-v /etc/localtime:/etc/localtime:ro \
{{ ceph_nfs_docker_extra_env }} \
--entrypoint=/usr/bin/ganesha.nfsd \
--name=ceph-nfs-{{ ceph_nfs_service_suffix | default(ansible_facts['hostname']) }} \
{{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
-F -L STDOUT
{% if container_binary == 'podman' %}
ExecStop=-/usr/bin/sh -c "/usr/bin/{{ container_binary }} rm -f `cat /%t/%n-cid`"
{% else %}
ExecStopPost=-/usr/bin/{{ container_binary }} stop ceph-nfs-%i
{% endif %}
KillMode=none
Restart=always
RestartSec=10s
TimeoutStartSec=120
TimeoutStopSec=15
{% if container_binary == 'podman' %}
Type=forking
PIDFile=/%t/%n-pid
{% endif %}
[Install]
WantedBy=multi-user.target
| guits | 5cd692dcdc8dd55036b8c283f1bca56f79965c1d | 23a8bbc6c59d78e982f343c06cfb5fe8e86cb757 | need to preserve this line | guits | 11 |
ceph/ceph-ansible | 7,326 | common: stop using ceph/daemon entrypoint | major refactor in order to make ceph-ansible use the `ceph/ceph` container image instead of `ceph/daemon` | null | 2022-10-07 12:52:53+00:00 | 2023-05-31 21:07:13+00:00 | roles/ceph-nfs/templates/ceph-nfs.service.j2 | [Unit]
Description=NFS-Ganesha file server
Documentation=http://github.com/nfs-ganesha/nfs-ganesha/wiki
{% if container_binary == 'docker' %}
After=docker.service network-online.target local-fs.target time-sync.target
Requires=docker.service
{% else %}
After=network-online.target local-fs.target time-sync.target
{% endif %}
Wants=network-online.target local-fs.target time-sync.target
[Service]
EnvironmentFile=-/etc/environment
{% if container_binary == 'podman' %}
ExecStartPre=-/usr/bin/rm -f /%t/%n-pid /%t/%n-cid
ExecStartPre=-/usr/bin/{{ container_binary }} rm --storage ceph-nfs-%i
ExecStartPre=-/usr/bin/mkdir -p /var/log/ceph /var/log/ganesha
{% endif %}
ExecStartPre=-/usr/bin/{{ container_binary }} rm ceph-nfs-%i
ExecStartPre={{ '/bin/mkdir' if ansible_facts['os_family'] == 'Debian' else '/usr/bin/mkdir' }} -p /etc/ceph /etc/ganesha /var/lib/nfs/ganesha /var/log/ganesha
ExecStart=/usr/bin/{{ container_binary }} run --rm --net=host \
{% if container_binary == 'podman' %}
-d --log-driver journald --conmon-pidfile /%t/%n-pid --cidfile /%t/%n-cid \
{% endif %}
--pids-limit={{ 0 if container_binary == 'podman' else -1 }} \
-v /etc/ceph:/etc/ceph:z \
-v /var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring:/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring:z \
-v /var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}/keyring:/etc/ceph/keyring:z \
-v /etc/ganesha:/etc/ganesha:z \
-v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket \
-v /var/run/ceph:/var/run/ceph:z \
-v /var/log/ceph:/var/log/ceph:z \
-v /var/log/ganesha:/var/log/ganesha:z \
-v /etc/localtime:/etc/localtime:ro \
{{ ceph_nfs_docker_extra_env }} \
--entrypoint=/usr/bin/ganesha.nfsd \
--name=ceph-nfs-{{ ceph_nfs_service_suffix | default(ansible_facts['hostname']) }} \
{{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
-F -L STDOUT
{% if container_binary == 'podman' %}
ExecStop=-/usr/bin/sh -c "/usr/bin/{{ container_binary }} rm -f `cat /%t/%n-cid`"
{% else %}
ExecStopPost=-/usr/bin/{{ container_binary }} stop ceph-nfs-%i
{% endif %}
KillMode=none
Restart=always
RestartSec=10s
TimeoutStartSec=120
TimeoutStopSec=15
{% if container_binary == 'podman' %}
Type=forking
PIDFile=/%t/%n-pid
{% endif %}
[Install]
WantedBy=multi-user.target
| [Unit]
Description=NFS-Ganesha file server
Documentation=http://github.com/nfs-ganesha/nfs-ganesha/wiki
{% if container_binary == 'docker' %}
After=docker.service network-online.target local-fs.target time-sync.target
Requires=docker.service
{% else %}
After=network-online.target local-fs.target time-sync.target
{% endif %}
Wants=network-online.target local-fs.target time-sync.target
[Service]
EnvironmentFile=-/etc/environment
{% if container_binary == 'podman' %}
ExecStartPre=-/usr/bin/rm -f /%t/%n-pid /%t/%n-cid
ExecStartPre=-/usr/bin/{{ container_binary }} rm --storage ceph-nfs-%i
ExecStartPre=-/usr/bin/mkdir -p /var/log/ceph /var/log/ganesha
{% endif %}
ExecStartPre=-/usr/bin/{{ container_binary }} rm ceph-nfs-%i
ExecStartPre={{ '/bin/mkdir' if ansible_facts['os_family'] == 'Debian' else '/usr/bin/mkdir' }} -p /etc/ceph /etc/ganesha /var/lib/nfs/ganesha /var/log/ganesha
ExecStart=/usr/bin/{{ container_binary }} run --rm --net=host \
{% if container_binary == 'podman' %}
-d --log-driver journald --conmon-pidfile /%t/%n-pid --cidfile /%t/%n-cid \
{% endif %}
--pids-limit={{ 0 if container_binary == 'podman' else -1 }} \
-v /etc/ceph:/etc/ceph:z \
-v /var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring:/var/lib/ceph/radosgw/{{ cluster }}-rgw.{{ ansible_facts['hostname'] }}/keyring:z \
-v /var/lib/ceph/radosgw/{{ cluster }}-nfs.{{ ansible_facts['hostname'] }}/keyring:/etc/ceph/keyring:z \
-v /etc/ganesha:/etc/ganesha:z \
-v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket \
-v /var/run/ceph:/var/run/ceph:z \
-v /var/log/ceph:/var/log/ceph:z \
-v /var/log/ganesha:/var/log/ganesha:z \
-v /etc/localtime:/etc/localtime:ro \
{{ ceph_nfs_docker_extra_env }} \
--entrypoint=/usr/bin/ganesha.nfsd \
--name=ceph-nfs-{{ ceph_nfs_service_suffix | default(ansible_facts['hostname']) }} \
{{ ceph_docker_registry }}/{{ ceph_docker_image }}:{{ ceph_docker_image_tag }} \
-F -L STDOUT
{% if container_binary == 'podman' %}
ExecStop=-/usr/bin/sh -c "/usr/bin/{{ container_binary }} rm -f `cat /%t/%n-cid`"
{% else %}
ExecStopPost=-/usr/bin/{{ container_binary }} stop ceph-nfs-%i
{% endif %}
KillMode=none
Restart=always
RestartSec=10s
TimeoutStartSec=120
TimeoutStopSec=15
{% if container_binary == 'podman' %}
Type=forking
PIDFile=/%t/%n-pid
{% endif %}
[Install]
WantedBy=multi-user.target
| guits | 5cd692dcdc8dd55036b8c283f1bca56f79965c1d | 23a8bbc6c59d78e982f343c06cfb5fe8e86cb757 | previously, the "start_nfs" script was starting idmapd as well; won't that be required? Also did this solution support nfsv3? if yes, statd and rpcbind are necessary as well? | gouthampacha | 12 |