Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

# -*- coding: utf-8 -*- 

# Copyright (C) 1998-2019 by the Free Software Foundation, Inc. 

# 

# This file is part of Postorius. 

# 

# Postorius is free software: you can redistribute it and/or modify it under 

# the terms of the GNU General Public License as published by the Free 

# Software Foundation, either version 3 of the License, or (at your option) 

# any later version. 

# 

# Postorius is distributed in the hope that it will be useful, but WITHOUT 

# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 

# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 

# more details. 

# 

# You should have received a copy of the GNU General Public License along with 

# Postorius. If not, see <http://www.gnu.org/licenses/>. 

 

 

import csv 

import email.utils 

import logging 

 

from django.conf import settings 

from django.contrib import messages 

from django.contrib.auth.decorators import login_required 

from django.core.exceptions import ValidationError 

from django.core.validators import validate_email 

from django.forms import formset_factory 

from django.http import Http404, HttpResponse 

from django.shortcuts import redirect, render 

from django.urls import reverse 

from django.utils.decorators import method_decorator 

from django.utils.six.moves.urllib.error import HTTPError 

from django.utils.translation import gettext as _ 

from django.views.decorators.http import require_http_methods 

 

from allauth.account.models import EmailAddress 

from django_mailman3.lib.mailman import get_mailman_client 

from django_mailman3.lib.paginator import MailmanPaginator, paginate 

 

from postorius.auth.decorators import ( 

list_moderator_required, list_owner_required, superuser_required) 

from postorius.auth.mixins import ListOwnerMixin 

from postorius.forms import ( 

AlterMessagesForm, ArchiveSettingsForm, DigestSettingsForm, 

DMARCMitigationsForm, ListAddBanForm, ListAnonymousSubscribe, 

ListAutomaticResponsesForm, ListHeaderMatchForm, ListHeaderMatchFormset, 

ListIdentityForm, ListMassRemoval, ListMassSubscription, ListNew, 

ListSubscribe, ListSubscriptionPolicyForm, MemberForm, MemberModeration, 

MessageAcceptanceForm, MultipleChoiceForm, UserPreferences) 

from postorius.forms.list_forms import ACTION_CHOICES 

from postorius.models import Domain, List, Mailman404Error, Style 

from postorius.views.generic import MailingListView 

 

 

logger = logging.getLogger(__name__) 

 

 

class TokenOwner: 

"""Who 'owns' the token returned from the registrar?""" 

subscriber = 'subscriber' 

moderator = 'moderator' 

 

 

class ListMembersViews(ListOwnerMixin, MailingListView): 

 

# List of allowed roles for the memberships. The string value matches the 

# exact value Core's REST API expects. 

allowed_roles = ['owner', 'moderator', 'member', 'nonmember'] 

 

def _prepare_query(self, request): 

"""Prepare regex based query to search partial email addresses. 

 

Core's `members/find` API allows searching for memberships based on 

regex. This methods prepares a valid regex to pass on the the REST API. 

""" 

if request.GET.get('q'): 

query = request.GET['q'] 

if "*" not in query: 

query = '*{}*'.format(query) 

else: 

query = '' 

 

return query 

 

def get(self, request, list_id, role): 

"""Handle GET for Member view. 

 

This includes all the membership roles (self.allowed_roles). 

""" 

member_form = MemberForm() 

# If the role is misspelled, redirect to the default subscribers. 

if role not in self.allowed_roles: 

return redirect('list_members', list_id, 'member') 

context = dict() 

context['list'] = self.mailing_list 

context['role'] = role 

context['member_form'] = member_form 

context['page_title'] = _('List {}s'.format(role.capitalize())) 

context['query'] = self._prepare_query(request) 

 

def find_method(count, page): 

return self.mailing_list.find_members( 

context['query'], role=role, count=count, page=page) 

 

context['members'] = paginate( 

find_method, 

request.GET.get('page', 1), 

request.GET.get('count', 25), 

paginator_class=MailmanPaginator) 

context['page_subtitle'] = '({})'.format( 

context['members'].paginator.count) 

context['form_action'] = _('Add {}'.format(role)) 

if context['query']: 

context['empty_error'] = _( 

'No {}s were found matching the search.'.format(role)) 

else: 

context['empty_error'] = _('List has no {}s'.format(role)) 

 

return render(request, 'postorius/lists/members.html', context) 

 

def _member_post(self, request, role): 

"""Handle POST for members. Unsubscribe all the members selected.""" 

form = MultipleChoiceForm(request.POST) 

if form.is_valid(): 

members = form.cleaned_data['choices'] 

for member in members: 

self.mailing_list.unsubscribe(member) 

messages.success( 

request, 

_('The selected members have been unsubscribed')) 

return redirect('list_members', self.mailing_list.list_id, role) 

 

def _non_member_post(self, request, role): 

"""Handle POST for membership roles owner, moderator and non-member. 

 

Add memberships if the form is valid otherwise redirect to list_members 

page with an error message. 

""" 

member_form = MemberForm(request.POST) 

if member_form.is_valid(): 

try: 

self.mailing_list.add_role( 

role=role, 

address=member_form.cleaned_data['email'], 

display_name=member_form.cleaned_data['display_name']) 

messages.success( 

request, 

_('{0}s has been added with the role {1}s'.format( 

member_form.cleaned_data['email'], role))) 

except HTTPError as e: 

messages.error(request, e.msg) 

else: 

messages.error(request, member_form.errors) 

return redirect('list_members', self.mailing_list.list_id, role) 

 

def post(self, request, list_id, role=None): 

"""Handle POST for list members page. 

 

List members page have more than one forms, depending on the membership 

type. 

 

- Regular subscribers have a MultipleChoiceForm, which returns a list 

of emails that needs to be unsubscribed from the MailingList. This is 

handled by :func:`self._member_post` method. 

 

- Owners, moderators and non-members have a MemberForm which allows 

adding new members with the given roles. This is handled by 

:func:`self._non_member_post` method. 

 

""" 

if role not in self.allowed_roles: 

return redirect('list_members', list_id, 'member') 

 

if role in ('member'): 

return self._member_post(request, role) 

else: 

return self._non_member_post(request, role) 

 

 

@login_required 

@list_owner_required 

def list_member_options(request, list_id, email): 

template_name = 'postorius/lists/memberoptions.html' 

mm_list = List.objects.get_or_404(fqdn_listname=list_id) 

try: 

mm_member = mm_list.find_members(address=email)[0] 

member_prefs = mm_member.preferences 

except (ValueError, IndexError): 

raise Http404(_('Member does not exist')) 

except Mailman404Error: 

return render(request, template_name, {'nolists': 'true'}) 

initial_moderation = dict([ 

(key, getattr(mm_member, key)) for key in MemberModeration.base_fields 

]) 

if request.method == 'POST': 

if request.POST.get("formname") == 'preferences': 

preferences_form = UserPreferences( 

request.POST, preferences=member_prefs) 

if preferences_form.is_valid(): 

try: 

preferences_form.save() 

except HTTPError as e: 

messages.error(request, e.msg) 

else: 

messages.success(request, _("The member's preferences" 

" have been updated.")) 

return redirect('list_member_options', list_id, email) 

elif request.POST.get("formname") == 'moderation': 

moderation_form = MemberModeration( 

request.POST, initial=initial_moderation) 

if moderation_form.is_valid(): 

if not moderation_form.has_changed(): 

messages.info( 

request, _("No change to the member's moderation.")) 

return redirect('list_member_options', list_id, email) 

for key in list(moderation_form.fields.keys()): 

# In general, it would be a very bad idea to loop over the 

# fields and try to set them one by one, However, 

# moderation form has only one field. 

setattr(mm_member, key, moderation_form.cleaned_data[key]) 

try: 

mm_member.save() 

except HTTPError as e: 

messages.error(request, e.msg) 

else: 

messages.success(request, _("The member's moderation " 

"settings have been updated.")) 

return redirect('list_member_options', list_id, email) 

else: 

preferences_form = UserPreferences(preferences=member_prefs) 

moderation_form = MemberModeration(initial=initial_moderation) 

return render(request, template_name, { 

'mm_member': mm_member, 

'list': mm_list, 

'preferences_form': preferences_form, 

'moderation_form': moderation_form, 

}) 

 

 

class ListSummaryView(MailingListView): 

"""Shows common list metrics. 

""" 

 

def get(self, request, list_id): 

data = {'list': self.mailing_list, 

'user_subscribed': False, 

'subscribed_address': None, 

'public_archive': False, 

'hyperkitty_enabled': False} 

if self.mailing_list.settings['archive_policy'] == 'public': 

data['public_archive'] = True 

if (getattr(settings, 'TESTING', False) and # noqa: W504 

'hyperkitty' not in settings.INSTALLED_APPS): 

# avoid systematic test failure when HyperKitty is installed 

# (missing VCR request, see below). 

list(self.mailing_list.archivers) 

if ('hyperkitty' in settings.INSTALLED_APPS and # noqa: W504 

'hyperkitty' in self.mailing_list.archivers and # noqa: W504 

self.mailing_list.archivers['hyperkitty']): 

data['hyperkitty_enabled'] = True 

if request.user.is_authenticated: 

user_emails = EmailAddress.objects.filter( 

user=request.user, verified=True).order_by( 

"email").values_list("email", flat=True) 

pending_requests = [r['email'] for r in self.mailing_list.requests] 

for address in user_emails: 

if address in pending_requests: 

data['user_request_pending'] = True 

break 

try: 

self.mailing_list.get_member(address) 

except ValueError: 

pass 

else: 

data['user_subscribed'] = True 

data['subscribed_address'] = address 

break # no need to test more addresses 

data['subscribe_form'] = ListSubscribe(user_emails) 

else: 

user_emails = None 

data['anonymous_subscription_form'] = ListAnonymousSubscribe() 

return render(request, 'postorius/lists/summary.html', data) 

 

 

class ChangeSubscriptionView(MailingListView): 

"""Change mailing list subscription 

""" 

 

@method_decorator(login_required) 

def post(self, request, list_id): 

try: 

user_emails = EmailAddress.objects.filter( 

user=request.user, verified=True).order_by( 

"email").values_list("email", flat=True) 

form = ListSubscribe(user_emails, request.POST) 

# Find the currently subscribed email 

old_email = None 

for address in user_emails: 

try: 

self.mailing_list.get_member(address) 

except ValueError: 

pass 

else: 

old_email = address 

break # no need to test more addresses 

assert old_email is not None 

if form.is_valid(): 

email = form.cleaned_data['email'] 

if old_email == email: 

messages.error(request, _('You are already subscribed')) 

else: 

self.mailing_list.unsubscribe(old_email) 

# Since the action is done via the web UI, no email 

# confirmation is needed. 

response = self.mailing_list.subscribe( 

email, pre_confirmed=True) 

if (type(response) == dict and # noqa: W504 

response.get('token_owner') == TokenOwner.moderator): # noqa: E501 

messages.success( 

request, _('Your request to change the email for' 

' this subscription was submitted and' 

' is waiting for moderator approval.')) 

else: 

messages.success(request, 

_('Subscription changed to %s') % 

email) 

else: 

messages.error(request, 

_('Something went wrong. Please try again.')) 

except HTTPError as e: 

messages.error(request, e.msg) 

return redirect('list_summary', self.mailing_list.list_id) 

 

 

class ListSubscribeView(MailingListView): 

""" 

view name: `list_subscribe` 

""" 

 

@method_decorator(login_required) 

def post(self, request, list_id): 

""" 

Subscribes an email address to a mailing list via POST and 

redirects to the `list_summary` view. 

""" 

try: 

user_emails = EmailAddress.objects.filter( 

user=request.user, verified=True).order_by( 

"email").values_list("email", flat=True) 

form = ListSubscribe(user_emails, request.POST) 

if form.is_valid(): 

email = request.POST.get('email') 

response = self.mailing_list.subscribe( 

email, pre_verified=True, pre_confirmed=True) 

if (type(response) == dict and # noqa: W504 

response.get('token_owner') == TokenOwner.moderator): 

messages.success( 

request, _('Your subscription request has been' 

' submitted and is waiting for moderator' 

' approval.')) 

else: 

messages.success(request, 

_('You are subscribed to %s.') % 

self.mailing_list.fqdn_listname) 

else: 

messages.error(request, 

_('Something went wrong. Please try again.')) 

except HTTPError as e: 

messages.error(request, e.msg) 

return redirect('list_summary', self.mailing_list.list_id) 

 

 

class ListAnonymousSubscribeView(MailingListView): 

""" 

view name: `list_anonymous_subscribe` 

""" 

 

def post(self, request, list_id): 

""" 

Subscribes an email address to a mailing list via POST and 

redirects to the `list_summary` view. 

This view is used for unauthenticated users and asks Mailman core to 

verify the supplied email address. 

""" 

try: 

form = ListAnonymousSubscribe(request.POST) 

if form.is_valid(): 

email = form.cleaned_data.get('email') 

self.mailing_list.subscribe(email, pre_verified=False, 

pre_confirmed=False) 

messages.success(request, _('Please check your inbox for ' 

'further instructions')) 

else: 

messages.error(request, 

_('Something went wrong. Please try again.')) 

except HTTPError as e: 

messages.error(request, e.msg) 

return redirect('list_summary', self.mailing_list.list_id) 

 

 

class ListUnsubscribeView(MailingListView): 

 

"""Unsubscribe from a mailing list.""" 

 

@method_decorator(login_required) 

def post(self, request, *args, **kwargs): 

email = request.POST['email'] 

try: 

self.mailing_list.unsubscribe(email) 

messages.success(request, _('%s has been unsubscribed' 

' from this list.') % email) 

except ValueError as e: 

messages.error(request, e) 

return redirect('list_summary', self.mailing_list.list_id) 

 

 

@login_required 

@list_owner_required 

def list_mass_subscribe(request, list_id): 

mailing_list = List.objects.get_or_404(fqdn_listname=list_id) 

if request.method == 'POST': 

form = ListMassSubscription(request.POST) 

if form.is_valid(): 

for data in form.cleaned_data['emails']: 

try: 

# Parse the data to get the address and the display name 

display_name, address = email.utils.parseaddr(data) 

validate_email(address) 

mailing_list.subscribe(address=address, 

display_name=display_name, 

pre_verified=True, 

pre_confirmed=True, 

pre_approved=True) 

messages.success( 

request, _('The address %(address)s has been' 

' subscribed to %(list)s.') % 

{'address': address, 

'list': mailing_list.fqdn_listname}) 

except HTTPError as e: 

messages.error(request, e) 

except ValidationError: 

messages.error(request, _('The email address %s' 

' is not valid.') % address) 

else: 

form = ListMassSubscription() 

return render(request, 'postorius/lists/mass_subscribe.html', 

{'form': form, 'list': mailing_list}) 

 

 

class ListMassRemovalView(MailingListView): 

 

"""Class For Mass Removal""" 

 

@method_decorator(login_required) 

@method_decorator(list_owner_required) 

def get(self, request, *args, **kwargs): 

form = ListMassRemoval() 

return render(request, 'postorius/lists/mass_removal.html', 

{'form': form, 'list': self.mailing_list}) 

 

@method_decorator(list_owner_required) 

def post(self, request, *args, **kwargs): 

form = ListMassRemoval(request.POST) 

if not form.is_valid(): 

messages.error(request, _('Please fill out the form correctly.')) 

else: 

for address in form.cleaned_data['emails']: 

try: 

validate_email(address) 

self.mailing_list.unsubscribe(address.lower()) 

messages.success( 

request, _('The address %(address)s has been' 

' unsubscribed from %(list)s.') % 

{'address': address, 

'list': self.mailing_list.fqdn_listname}) 

except (HTTPError, ValueError) as e: 

messages.error(request, e) 

except ValidationError: 

messages.error(request, _('The email address %s' 

' is not valid.') % address) 

return redirect('mass_removal', self.mailing_list.list_id) 

 

 

def _perform_action(message_ids, action): 

for message_id in message_ids: 

action(message_id) 

 

 

@login_required 

@list_moderator_required 

def list_moderation(request, list_id, held_id=-1): 

mailing_list = List.objects.get_or_404(fqdn_listname=list_id) 

if request.method == 'POST': 

form = MultipleChoiceForm(request.POST) 

if form.is_valid(): 

message_ids = form.cleaned_data['choices'] 

try: 

if 'accept' in request.POST: 

_perform_action(message_ids, mailing_list.accept_message) 

messages.success(request, 

_('The selected messages were accepted')) 

elif 'reject' in request.POST: 

_perform_action(message_ids, mailing_list.reject_message) 

messages.success(request, 

_('The selected messages were rejected')) 

elif 'discard' in request.POST: 

_perform_action(message_ids, mailing_list.discard_message) 

messages.success(request, 

_('The selected messages were discarded')) 

except HTTPError: 

messages.error(request, _('Message could not be found')) 

else: 

form = MultipleChoiceForm() 

held_messages = paginate( 

mailing_list.get_held_page, 

request.GET.get('page'), request.GET.get('count'), 

paginator_class=MailmanPaginator) 

context = { 

'list': mailing_list, 

'held_messages': held_messages, 

'form': form, 

'ACTION_CHOICES': ACTION_CHOICES, 

} 

return render(request, 'postorius/lists/held_messages.html', context) 

 

 

@require_http_methods(['POST']) 

@login_required 

@list_moderator_required 

def moderate_held_message(request, list_id): 

"""Moderate one held message""" 

mailing_list = List.objects.get_or_404(fqdn_listname=list_id) 

msg = mailing_list.get_held_message(request.POST['msgid']) 

moderation_choice = request.POST.get('moderation_choice') 

if 'accept' in request.POST: 

mailing_list.accept_message(msg.request_id) 

messages.success(request, _('The message was accepted')) 

elif 'reject' in request.POST: 

mailing_list.reject_message(msg.request_id) 

messages.success(request, _('The message was rejected')) 

elif 'discard' in request.POST: 

mailing_list.discard_message(msg.request_id) 

messages.success(request, _('The message was discarded')) 

moderation_choices = dict(ACTION_CHOICES) 

if moderation_choice in moderation_choices: 

try: 

member = mailing_list.get_member(msg.sender) 

member.moderation_action = moderation_choice 

member.save() 

messages.success( 

request, 

_('Moderation action for {} set to {}'.format( 

member, moderation_choices[moderation_choice]))) 

except ValueError as e: 

messages.error( 

request, 

_('Failed to set moderation action: {}'.format(e))) 

return redirect('list_held_messages', list_id) 

 

 

@login_required 

@list_owner_required 

def csv_view(request, list_id): 

"""Export all the subscriber in csv 

""" 

mm_lists = List.objects.get_or_404(fqdn_listname=list_id) 

 

response = HttpResponse(content_type='text/csv') 

response['Content-Disposition'] = ( 

'attachment; filename="Subscribers.csv"') 

 

writer = csv.writer(response) 

if mm_lists: 

for i in mm_lists.members: 

writer.writerow([i.email]) 

 

return response 

 

 

def _get_choosable_domains(request): 

domains = Domain.objects.all() 

return [(d.mail_host, d.mail_host) for d in domains] 

 

 

def _get_choosable_styles(request): 

styles = Style.objects.all() 

options = [(style['name'], style['description']) 

for style in styles['styles']] 

# Reorder to put the default at the beginning 

for style_option in options: 

if style_option[0] == styles['default']: 

options.remove(style_option) 

options.insert(0, style_option) 

break 

return options 

 

 

@login_required 

@superuser_required 

def list_new(request, template='postorius/lists/new.html'): 

""" 

Add a new mailing list. 

If the request to the function is a GET request an empty form for 

creating a new list will be displayed. If the request method is 

POST the form will be evaluated. If the form is considered 

correct the list gets created and otherwise the form with the data 

filled in before the last POST request is returned. The user must 

be logged in to create a new list. 

""" 

mailing_list = None 

choosable_domains = [('', _('Choose a Domain'))] 

choosable_domains += _get_choosable_domains(request) 

choosable_styles = _get_choosable_styles(request) 

if request.method == 'POST': 

form = ListNew(choosable_domains, choosable_styles, request.POST) 

if form.is_valid(): 

# grab domain 

domain = Domain.objects.get_or_404( 

mail_host=form.cleaned_data['mail_host']) 

# creating the list 

try: 

mailing_list = domain.create_list( 

form.cleaned_data['listname'], 

style_name=form.cleaned_data['list_style']) 

mailing_list.add_owner(form.cleaned_data['list_owner']) 

list_settings = mailing_list.settings 

if form.cleaned_data['description']: 

list_settings["description"] = \ 

form.cleaned_data['description'] 

list_settings["advertised"] = form.cleaned_data['advertised'] 

list_settings.save() 

messages.success(request, _("List created")) 

return redirect("list_summary", 

list_id=mailing_list.list_id) 

# TODO catch correct Error class: 

except HTTPError as e: 

# Right now, there is no good way to detect that this is a 

# duplicate mailing list request other than checking the 

# reason for 400 error. 

if e.reason == b'Mailing list exists': 

form.add_error( 

'listname', _('Mailing List already exists.')) 

return render(request, template, {'form': form}) 

# Otherwise just render the generic error page. 

return render(request, 'postorius/errors/generic.html', 

{'error': e.msg}) 

else: 

messages.error(request, _('Please check the errors below')) 

else: 

form = ListNew(choosable_domains, choosable_styles, initial={ 

'list_owner': request.user.email, 

'advertised': True, 

}) 

return render(request, template, {'form': form}) 

 

 

def _unique_lists(lists): 

"""Return unique lists from a list of mailing lists.""" 

return {mlist.list_id: mlist for mlist in lists}.values() 

 

 

@login_required 

def list_index_authenticated(request): 

"""Index page for authenticated users. 

 

Index page for authenticated users is slightly different than 

un-authenticated ones. Authenticated users will see all their memberships 

in the index page. 

 

This view is not paginated and will show all the lists. 

 

""" 

role = request.GET.get('role', None) 

client = get_mailman_client() 

choosable_domains = _get_choosable_domains(request) 

 

# Get all the verified addresses of the user. 

user_emails = EmailAddress.objects.filter( 

user=request.user, verified=True).order_by( 

"email").values_list("email", flat=True) 

 

# Get all the mailing lists for the current user. 

all_lists = [] 

mail_host = request.get_host().split(':')[0] if ( 

getattr(settings, 'FILTER_VHOST', False)) else None 

for user_email in user_emails: 

try: 

all_lists.extend( 

client.find_lists(user_email, role=role, mail_host=mail_host)) 

except HTTPError: 

# No lists exist with the given role for the given user. 

pass 

# If the user has no list that they are subscriber/owner/moderator of, we 

# just redirect them to the index page with all lists. 

if len(all_lists) == 0 and role is None: 

return redirect(reverse('list_index') + '?all-lists') 

# Render the list index page. 

context = { 

'lists': _unique_lists(all_lists), 

'domain_count': len(choosable_domains), 

'role': role 

} 

return render( 

request, 

'postorius/index.html', 

context 

) 

 

 

def list_index(request, template='postorius/index.html'): 

"""Show a table of all public mailing lists.""" 

# TODO maxking: Figure out why does this view accept POST request and why 

# can't it be just a GET with list parameter. 

if request.method == 'POST': 

return redirect("list_summary", list_id=request.POST["list"]) 

# If the user is logged-in, show them only related lists in the index, 

# except role is present in requests.GET. 

if request.user.is_authenticated and 'all-lists' not in request.GET: 

return list_index_authenticated(request) 

 

def _get_list_page(count, page): 

client = get_mailman_client() 

advertised = not request.user.is_superuser 

mail_host = request.get_host().split(":")[0] if ( 

getattr(settings, 'FILTER_VHOST', False)) else None 

return client.get_list_page( 

advertised=advertised, mail_host=mail_host, count=count, page=page) 

 

lists = paginate( 

_get_list_page, request.GET.get('page'), request.GET.get('count'), 

paginator_class=MailmanPaginator) 

 

choosable_domains = _get_choosable_domains(request) 

 

return render(request, template, 

{'lists': lists, 

'all_lists': True, 

'domain_count': len(choosable_domains)}) 

 

 

@login_required 

@list_owner_required 

def list_delete(request, list_id): 

"""Deletes a list but asks for confirmation first. 

""" 

the_list = List.objects.get_or_404(fqdn_listname=list_id) 

if request.method == 'POST': 

the_list.delete() 

return redirect("list_index") 

else: 

submit_url = reverse('list_delete', 

kwargs={'list_id': list_id}) 

cancel_url = reverse('list_index',) 

return render(request, 'postorius/lists/confirm_delete.html', 

{'submit_url': submit_url, 'cancel_url': cancel_url, 

'list': the_list}) 

 

 

@login_required 

@list_moderator_required 

def list_pending_confirmations(request, list_id): 

"""Shows a list of subscription requests. 

""" 

return _list_subscriptions( 

request=request, 

list_id=list_id, 

token_owner=TokenOwner.subscriber, 

template='postorius/lists/pending_confirmations.html', 

page_title=_('Subscriptions pending user confirmation'), 

) 

 

 

@login_required 

@list_moderator_required 

def list_subscription_requests(request, list_id): 

"""Shows a list of subscription requests.""" 

return _list_subscriptions( 

request=request, 

list_id=list_id, 

token_owner=TokenOwner.moderator, 

template='postorius/lists/subscription_requests.html', 

page_title=_('Subscriptions pending approval'), 

) 

 

 

def _list_subscriptions(request, list_id, token_owner, template, page_title): 

m_list = List.objects.get_or_404(fqdn_listname=list_id) 

requests = [req 

for req in m_list.requests 

if req['token_owner'] == token_owner] 

paginated_requests = paginate( 

requests, 

request.GET.get('page'), 

request.GET.get('count', 25)) 

page_subtitle = '(%d)' % len(requests) 

return render(request, template, 

{'list': m_list, 

'paginated_requests': paginated_requests, 

'page_title': page_title, 

'page_subtitle': page_subtitle}) 

 

 

@login_required 

@list_moderator_required 

def handle_subscription_request(request, list_id, request_id, action): 

""" 

Handle a subscription request. Possible actions: 

- accept 

- defer 

- reject 

- discard 

""" 

confirmation_messages = { 

'accept': _('The request has been accepted.'), 

'reject': _('The request has been rejected.'), 

'discard': _('The request has been discarded.'), 

'defer': _('The request has been defered.'), 

} 

assert action in confirmation_messages 

try: 

m_list = List.objects.get_or_404(fqdn_listname=list_id) 

# Moderate request and add feedback message to session. 

m_list.moderate_request(request_id, action) 

messages.success(request, confirmation_messages[action]) 

except HTTPError as e: 

if e.code == 409: 

messages.success(request, 

_('The request was already moderated: %s') 

% e.reason) 

else: 

messages.error(request, _('The request could not be moderated: %s') 

% e.reason) 

return redirect('list_subscription_requests', m_list.list_id) 

 

 

SETTINGS_SECTION_NAMES = ( 

('list_identity', _('List Identity')), 

('automatic_responses', _('Automatic Responses')), 

('alter_messages', _('Alter Messages')), 

('dmarc_mitigations', _('DMARC Mitigations')), 

('digest', _('Digest')), 

('message_acceptance', _('Message Acceptance')), 

('archiving', _('Archiving')), 

('subscription_policy', _('Subscription Policy')), 

) 

 

SETTINGS_FORMS = { 

'list_identity': ListIdentityForm, 

'automatic_responses': ListAutomaticResponsesForm, 

'alter_messages': AlterMessagesForm, 

'dmarc_mitigations': DMARCMitigationsForm, 

'digest': DigestSettingsForm, 

'message_acceptance': MessageAcceptanceForm, 

'archiving': ArchiveSettingsForm, 

'subscription_policy': ListSubscriptionPolicyForm, 

} 

 

 

@login_required 

@list_owner_required 

def list_settings(request, list_id=None, visible_section=None, 

template='postorius/lists/settings.html'): 

""" 

View and edit the settings of a list. 

The function requires the user to be logged in and have the 

permissions necessary to perform the action. 

 

Use /<NAMEOFTHESECTION>/<NAMEOFTHEOPTION> 

to show only parts of the settings 

<param> is optional / is used to differ in between section and option might 

result in using //option 

""" 

if visible_section is None: 

visible_section = 'list_identity' 

try: 

form_class = SETTINGS_FORMS[visible_section] 

except KeyError: 

raise Http404('No such settings section') 

m_list = List.objects.get_or_404(fqdn_listname=list_id) 

list_settings = m_list.settings 

initial_data = dict((key, value) for key, value in list_settings.items()) 

# List settings are grouped an processed in different forms. 

if request.method == 'POST': 

form = form_class(request.POST, mlist=m_list, initial=initial_data) 

if form.is_valid(): 

try: 

for key in form.changed_data: 

if key in form_class.mlist_properties: 

setattr(m_list, key, form.cleaned_data[key]) 

else: 

list_settings[key] = form.cleaned_data[key] 

list_settings.save() 

messages.success(request, _('The settings have been updated.')) 

except HTTPError as e: 

messages.error( 

request, 

_('An error occured: ') + e.reason) 

return redirect('list_settings', m_list.list_id, visible_section) 

else: 

form = form_class(initial=initial_data, mlist=m_list) 

 

return render(request, template, { 

'form': form, 

'section_names': SETTINGS_SECTION_NAMES, 

'list': m_list, 

'visible_section': visible_section, 

}) 

 

 

@login_required 

@list_owner_required 

def remove_role(request, list_id=None, role=None, address=None, 

template='postorius/lists/confirm_remove_role.html'): 

"""Removes a list moderator or owner.""" 

the_list = List.objects.get_or_404(fqdn_listname=list_id) 

redirect_on_success = redirect('list_members', the_list.list_id, role) 

roster = getattr(the_list, '{}s'.format(role)) 

all_emails = [each.email for each in roster] 

if address not in all_emails: 

messages.error(request, 

_('The user %(email)s is not in the %(role)s group') 

% {'email': address, 'role': role}) 

return redirect('list_members', the_list.list_id, role) 

 

if role == 'owner': 

if len(roster) == 1: 

messages.error(request, _('Removing the last owner is impossible')) 

return redirect('list_members', the_list.list_id, role) 

user_emails = EmailAddress.objects.filter( 

user=request.user, verified=True).order_by( 

"email").values_list("email", flat=True) 

if address in user_emails: 

# The user is removing themselves, redirect to the list info page 

# because they won't have access to the members page anyway. 

redirect_on_success = redirect('list_summary', the_list.list_id) 

 

if request.method == 'POST': 

try: 

the_list.remove_role(role, address) 

except HTTPError as e: 

messages.error(request, _('The user could not be removed: %(msg)s') 

% {'msg': e.msg}) 

return redirect('list_members', the_list.list_id, role) 

messages.success(request, _('The user %(address)s has been removed' 

' from the %(role)s group.') 

% {'address': address, 'role': role}) 

return redirect_on_success 

return render(request, template, 

{'role': role, 'address': address, 

'list_id': the_list.list_id}) 

 

 

@login_required 

@list_owner_required 

def remove_all_subscribers(request, list_id): 

 

"""Empty the list by unsubscribing all members.""" 

 

mlist = List.objects.get_or_404(fqdn_listname=list_id) 

if len(mlist.members) == 0: 

messages.error(request, 

_('No member is subscribed to the list currently.')) 

return redirect('mass_removal', mlist.list_id) 

if request.method == 'POST': 

try: 

# TODO maxking: This doesn't scale. Either the Core should provide 

# an endpoint to remove all subscribers or there should be some 

# better way to do this. Maybe, Core can take a list of email 

# addresses in batches of 50 and unsubscribe all of them. 

for names in mlist.members: 

mlist.unsubscribe(names.email) 

messages.success(request, _('All members have been' 

' unsubscribed from the list.')) 

return redirect('list_members', mlist.list_id, 'subscriber') 

except Exception as e: 

messages.error(request, e) 

return render(request, 

'postorius/lists/confirm_removeall_subscribers.html', 

{'list': mlist}) 

 

 

@login_required 

@list_owner_required 

def list_bans(request, list_id): 

""" 

Ban or unban email addresses. 

""" 

# Get the list and cache the archivers property. 

m_list = List.objects.get_or_404(fqdn_listname=list_id) 

ban_list = m_list.bans 

 

# Process form submission. 

if request.method == 'POST': 

if 'add' in request.POST: 

addban_form = ListAddBanForm(request.POST) 

if addban_form.is_valid(): 

try: 

ban_list.add(addban_form.cleaned_data['email']) 

messages.success(request, _( 

'The email {} has been banned.'.format( 

addban_form.cleaned_data['email']))) 

except HTTPError as e: 

messages.error( 

request, _('An error occured: %s') % e.reason) 

except ValueError as e: 

messages.error(request, _('Invalid data: %s') % e) 

return redirect('list_bans', list_id) 

elif 'del' in request.POST: 

try: 

ban_list.remove(request.POST['email']) 

messages.success(request, _( 

'The email {} has been un-banned'.format( 

request.POST['email']))) 

except HTTPError as e: 

messages.error(request, _('An error occured: %s') % e.reason) 

except ValueError as e: 

messages.error(request, _('Invalid data: %s') % e) 

return redirect('list_bans', list_id) 

else: 

addban_form = ListAddBanForm(initial=request.GET) 

banned_addresses = paginate( 

list(ban_list), request.GET.get('page'), request.GET.get('count')) 

return render(request, 'postorius/lists/bans.html', 

{'list': m_list, 

'addban_form': addban_form, 

'banned_addresses': banned_addresses, 

}) 

 

 

@login_required 

@list_owner_required 

def list_header_matches(request, list_id): 

""" 

View and edit the list's header matches. 

""" 

m_list = List.objects.get_or_404(fqdn_listname=list_id) 

header_matches = m_list.header_matches 

HeaderMatchFormset = formset_factory( 

ListHeaderMatchForm, extra=1, can_delete=True, can_order=True, 

formset=ListHeaderMatchFormset) 

initial_data = [ 

dict([ 

(key, getattr(hm, key)) for key in ListHeaderMatchForm.base_fields 

]) for hm in header_matches] 

 

# Process form submission. 

if request.method == 'POST': 

formset = HeaderMatchFormset(request.POST, initial=initial_data) 

if formset.is_valid(): 

if not formset.has_changed(): 

return redirect('list_header_matches', list_id) 

# Purge the existing header_matches 

header_matches.clear() 

# Add the ones in the form 

 

def form_order(f): 

# If ORDER is None (new header match), add it last. 

return f.cleaned_data.get('ORDER') or len(formset.forms) 

errors = [] 

for form in sorted(formset, key=form_order): 

if 'header' not in form.cleaned_data: 

# The new header match form was not filled 

continue 

if form.cleaned_data.get('DELETE'): 

continue 

try: 

header_matches.add( 

header=form.cleaned_data['header'], 

pattern=form.cleaned_data['pattern'], 

action=form.cleaned_data['action'], 

) 

except HTTPError as e: 

errors.append(e) 

for e in errors: 

messages.error( 

request, _('An error occured: %s') % e.reason) 

if not errors: 

messages.success(request, _('The header matches were' 

' successfully modified.')) 

return redirect('list_header_matches', list_id) 

else: 

formset = HeaderMatchFormset(initial=initial_data) 

# Adapt the last form to create new matches 

form_new = formset.forms[-1] 

form_new.fields['header'].widget.attrs['placeholder'] = _('New header') 

form_new.fields['pattern'].widget.attrs['placeholder'] = _('New pattern') 

del form_new.fields['ORDER'] 

del form_new.fields['DELETE'] 

 

return render(request, 'postorius/lists/header_matches.html', { 

'list': m_list, 

'formset': formset, 

})