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

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

"""Controllers related to viewing lists of bookmarks""" 

import logging 

 

from datetime import datetime 

from pyramid.settings import asbool 

from pyramid.view import view_config 

from sqlalchemy.exc import IntegrityError 

from sqlalchemy.orm import contains_eager 

from StringIO import StringIO 

 

from bookie.bcelery import tasks 

from bookie.lib.access import api_auth 

from bookie.lib.applog import AuthLog 

from bookie.lib.applog import BmarkLog 

from bookie.lib.message import ReactivateMsg 

from bookie.lib.message import InvitationMsg 

from bookie.lib.readable import ReadContent 

from bookie.lib.tagcommands import Commander 

 

from bookie.models import Bmark 

from bookie.models import BmarkMgr 

from bookie.models import DBSession 

from bookie.models import NoResultFound 

from bookie.models import Readable 

from bookie.models import TagMgr 

from bookie.models.applog import AppLogMgr 

from bookie.models.auth import ActivationMgr 

from bookie.models.auth import get_random_word 

from bookie.models.auth import User 

from bookie.models.auth import UserMgr 

from bookie.models.queue import ImportQueueMgr 

 

from bookie.models.fulltext import get_fulltext_handler 

 

LOG = logging.getLogger(__name__) 

RESULTS_MAX = 10 

HARD_MAX = 100 

 

 

def _check_with_content(params): 

    """Verify that we should be checking with content""" 

    if 'with_content' in params and params['with_content'] != 'false': 

        return True 

    else: 

        return False 

 

 

@view_config(route_name="api_ping", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def ping(request): 

    """Verify that you've setup your api correctly and verified 

 

    """ 

    return { 

        'success': True, 

        'message': 'Looks good' 

    } 

 

 

@view_config(route_name="api_ping_missing_user", renderer="json") 

def ping_missing_user(request): 

    """You ping'd but were missing the username in the url for some reason. 

 

    """ 

    return { 

        'success': False, 

        'message': 'Missing username in your api url.' 

    } 

 

 

@view_config(route_name="api_ping_missing_api", renderer="json") 

def ping_missing_api(request): 

    """You ping'd but didn't specify the actual api url. 

 

    """ 

    return { 

        'success': False, 

        'message': 'The API url should be /api/v1' 

    } 

 

 

@view_config(route_name="api_bmark_hash", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def bmark_get(request): 

    """Return a bookmark requested via hash_id 

 

    We need to return a nested object with parts 

        bmark 

            - readable 

    """ 

    rdict = request.matchdict 

    params = request.params 

 

    hash_id = rdict.get('hash_id', None) 

    username = request.user.username 

 

    # the hash id will always be there or the route won't match 

    bookmark = BmarkMgr.get_by_hash(hash_id, 

                                    username=username) 

 

    last_bmark = {} 

    if 'last_bmark' in params and params['last_bmark'] != "false": 

        last = BmarkMgr.get_recent_bmark(username=username) 

        if last is not None: 

            last_bmark = {'last': dict(last)} 

 

    if bookmark is None: 

        request.response.status_int = 404 

        ret = {'error': "Bookmark for hash id {0} not found".format(hash_id)} 

        ret.update(last_bmark) 

        return ret 

    else: 

        return_obj = dict(bookmark) 

 

        if 'with_content' in params and params['with_content'] != 'false': 

            if bookmark.readable: 

                return_obj['readable'] = dict(bookmark.readable) 

 

        return_obj['tags'] = [dict(tag[1]) for tag in bookmark.tags.items()] 

 

        ret = {'bmark': return_obj} 

        ret.update(last_bmark) 

        return ret 

 

 

def _update_mark(mark, params): 

    """Update the bookmark found with settings passed in""" 

    mark.description = params.get('description', mark.description) 

    mark.extended = params.get('extended', mark.extended) 

 

    new_tag_str = params.get('tags', None) 

 

    # if the only new tags are commands, then don't erase the 

    # existing tags 

    # we need to process any commands associated as well 

    new_tags = TagMgr.from_string(new_tag_str) 

    found_cmds = Commander.check_commands(new_tags) 

 

    if new_tag_str and len(new_tags) == len(found_cmds): 

        # the all the new tags are command tags, just tack them on 

        # for processing, but don't touch existing tags 

        for command_tag in new_tags.values(): 

            mark.tags[command_tag.name] = command_tag 

    else: 

        if new_tag_str: 

            # in this case, rewrite the tags wit the new ones 

            mark.update_tags(new_tag_str) 

 

    return mark 

 

 

@view_config(route_name="api_bmark_add", renderer="json") 

@view_config(route_name="api_bmark_update", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def bmark_add(request): 

    """Add a new bookmark to the system""" 

    rdict = request.matchdict 

    if 'url' in request.params or 'hash_id' in request.params: 

        params = request.params 

    elif 'url' in request.json_body or 'hash_id' in request.json_body: 

        params = request.json_body 

    else: 

        request.response.status_int = 400 

        return { 

            'error': 'Bad Request: missing url', 

        } 

 

    user = request.user 

 

    if 'url' not in params and 'hash_id' not in rdict: 

        request.response.status_int = 400 

        return { 

            'error': 'Bad Request: missing url', 

        } 

 

    elif 'hash_id' in rdict: 

        try: 

            mark = BmarkMgr.get_by_hash(rdict['hash_id'], 

                                        username=user.username) 

            mark = _update_mark(mark, params) 

 

        except NoResultFound: 

            request.response.status_code = 404 

            return { 

                'error': 'Bookmark with hash id {0} not found.'.format( 

                         rdict['hash_id']) 

            } 

 

    else: 

        # check if we already have this 

        try: 

            mark = BmarkMgr.get_by_url(params['url'], 

                                       username=user.username) 

            mark = _update_mark(mark, params) 

 

        except NoResultFound: 

            # then let's store this thing 

            # if we have a dt param then set the date to be that manual 

            # date 

            if 'dt' in request.params: 

                # date format by delapi specs: 

                # CCYY-MM-DDThh:mm:ssZ 

                fmt = "%Y-%m-%dT%H:%M:%SZ" 

                stored_time = datetime.strptime(request.params['dt'], fmt) 

            else: 

                stored_time = None 

 

            # check to see if we know where this is coming from 

            inserted_by = params.get('inserted_by', 'unknown_api') 

 

            mark = BmarkMgr.store( 

                params['url'], 

                user.username, 

                params.get('description', ''), 

                params.get('extended', ''), 

                params.get('tags', ''), 

                dt=stored_time, 

                inserted_by=inserted_by, 

            ) 

 

        # we need to process any commands associated as well 

        commander = Commander(mark) 

        mark = commander.process() 

 

        # if we have content, stick it on the object here 

        if 'content' in params: 

            content = StringIO(params['content']) 

            content.seek(0) 

            parsed = ReadContent.parse(content, 

                                       content_type="text/html", 

                                       url=mark.hashed.url) 

 

            mark.readable = Readable() 

            mark.readable.content = parsed.content 

            mark.readable.content_type = parsed.content_type 

            mark.readable.status_code = parsed.status 

            mark.readable.status_message = parsed.status_message 

 

        # we need to flush here for new tag ids, etc 

        DBSession.flush() 

 

        mark_data = dict(mark) 

        mark_data['tags'] = [dict(mark.tags[tag]) for tag in mark.tags.keys()] 

 

        return { 

            'bmark': mark_data, 

            'location': request.route_url('bmark_readable', 

                                          hash_id=mark.hash_id, 

                                          username=user.username), 

        } 

 

 

@view_config(route_name="api_bmark_remove", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def bmark_remove(request): 

    """Remove this bookmark from the system""" 

    rdict = request.matchdict 

    user = request.user 

 

    try: 

        bmark = BmarkMgr.get_by_hash(rdict['hash_id'], 

                                     username=user.username) 

        DBSession.delete(bmark) 

        return { 

            'message': "done", 

        } 

 

    except NoResultFound: 

        request.response.status_code = 404 

        return { 

            'error': 'Bookmark with hash id {0} not found.'.format( 

                     rdict['hash_id']) 

        } 

 

 

@view_config(route_name="api_bmarks", renderer="json") 

@view_config(route_name="api_bmarks_user", renderer="json") 

@view_config(route_name="api_bmarks_tags", renderer="json") 

@view_config(route_name="api_bmarks_user_tags", renderer="json") 

@api_auth('api_key', UserMgr.get, anon=True) 

def bmark_recent(request, with_content=False): 

    """Get a list of the bmarks for the api call""" 

    rdict = request.matchdict 

    params = request.params 

 

    # check if we have a page count submitted 

    page = int(params.get('page', '0')) 

    count = int(params.get('count', RESULTS_MAX)) 

 

    # we only want to do the username if the username is in the url 

    username = rdict.get('username', None) 

 

    # thou shalt not have more then the HARD MAX 

    # @todo move this to the .ini as a setting 

    if count > HARD_MAX: 

        count = HARD_MAX 

 

    # do we have any tags to filter upon 

    tags = rdict.get('tags', None) 

 

    if isinstance(tags, str): 

        tags = [tags] 

 

    # if we don't have tags, we might have them sent by a non-js browser as a 

    # string in a query string 

    if not tags and 'tag_filter' in params: 

        tags = params.get('tag_filter').split() 

 

    # @todo fix this! 

    # if we allow showing of content the query hangs and fails on the 

    # postgres side. Need to check the query and figure out what's up. 

    # see bug #142 

    # We don't allow with_content by default because of this bug. 

    recent_list = BmarkMgr.find( 

        limit=count, 

        order_by=Bmark.stored.desc(), 

        page=page, 

        tags=tags, 

        username=username, 

        with_tags=True, 

    ) 

 

    result_set = [] 

 

    for res in recent_list: 

        return_obj = dict(res) 

        return_obj['tags'] = [dict(tag[1]) for tag in res.tags.items()] 

 

        # we should have the hashed information, we need the url and clicks as 

        # total clicks to send back 

        return_obj['url'] = res.hashed.url 

        return_obj['total_clicks'] = res.hashed.clicks 

 

        if with_content: 

            return_obj['readable'] = dict(res.readable) if res.readable else {} 

 

        result_set.append(return_obj) 

 

    return { 

        'bmarks': result_set, 

        'max_count': RESULTS_MAX, 

        'count': len(recent_list), 

        'page': page, 

        'tag_filter': tags, 

    } 

 

 

@view_config(route_name="api_bmarks_popular", renderer="json") 

@view_config(route_name="api_bmarks_popular_user", renderer="json") 

@api_auth('api_key', UserMgr.get, anon=True) 

def bmark_popular(request): 

    """Get a list of the most popular bmarks for the api call""" 

    rdict = request.matchdict 

    params = request.params 

 

    # check if we have a page count submitted 

    page = int(params.get('page', '0')) 

    count = int(params.get('count', RESULTS_MAX)) 

    with_content = _check_with_content(params) 

 

    if request.user and request.user.username: 

        username = request.user.username 

    else: 

        username = None 

 

    # thou shalt not have more then the HARD MAX 

    # @todo move this to the .ini as a setting 

    if count > HARD_MAX: 

        count = HARD_MAX 

 

    # do we have any tags to filter upon 

    tags = rdict.get('tags', None) 

 

    if isinstance(tags, str): 

        tags = [tags] 

 

    # if we don't have tags, we might have them sent by a non-js browser as a 

    # string in a query string 

    if not tags and 'tag_filter' in params: 

        tags = params.get('tag_filter').split() 

 

    popular_list = BmarkMgr.find( 

        limit=count, 

        order_by=Bmark.clicks.desc(), 

        page=page, 

        tags=tags, 

        username=username, 

        with_content=with_content, 

        with_tags=True, 

    ) 

 

    result_set = [] 

 

    for res in popular_list: 

        return_obj = dict(res) 

        return_obj['tags'] = [dict(tag[1]) for tag in res.tags.items()] 

 

        # the hashed object is there as well, we need to pull the url and 

        # clicks from it as total_clicks 

        return_obj['url'] = res.hashed.url 

        return_obj['total_clicks'] = res.hashed.clicks 

 

        if with_content: 

            return_obj['readable'] = dict(res.hashed.readable) 

 

        result_set.append(return_obj) 

 

    return { 

        'bmarks': result_set, 

        'max_count': RESULTS_MAX, 

        'count': len(popular_list), 

        'page': page, 

        'tag_filter': tags, 

    } 

 

 

@view_config(route_name="api_bmarks_export", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def bmark_export(request): 

    """Export via the api call to json dump 

 

    """ 

    username = request.user.username 

 

    bmark_list = BmarkMgr.user_dump(username) 

    # log that the user exported this 

    BmarkLog.export(username, username) 

 

    def build_bmark(bmark): 

        d = dict(bmark) 

        d['hashed'] = dict(bmark.hashed) 

        return d 

 

    return { 

        'bmarks': [build_bmark(bmark) for bmark in bmark_list], 

        'count': len(bmark_list), 

        'date': str(datetime.utcnow()) 

    } 

 

 

@view_config(route_name="api_extension_sync", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def extension_sync(request): 

    """Return a list of the bookmarks we know of in the system 

 

    For right now, send down a list of hash_ids 

 

    """ 

    username = request.user.username 

 

    hash_list = BmarkMgr.hash_list(username=username) 

    return { 

        'hash_list': [hash[0] for hash in hash_list] 

    } 

 

 

@view_config(route_name="api_bmark_search", renderer="json") 

@view_config(route_name="api_bmark_search_user", renderer="json") 

@api_auth('api_key', UserMgr.get, anon=True) 

def search_results(request): 

    """Search for the query terms in the matchdict/GET params 

 

    The ones in the matchdict win in the case that they both exist 

    but we'll fall back to query string search=XXX 

 

    with_content 

        is always GET and specifies if we're searching the fulltext of pages 

 

    """ 

    mdict = request.matchdict 

    rdict = request.GET 

 

    if 'terms' in mdict: 

        phrase = " ".join(mdict['terms']) 

    else: 

        phrase = rdict.get('search', '') 

 

    if request.user and request.user.username: 

        username = request.user.username 

    else: 

        username = None 

 

    # with content is always in the get string 

    search_content = asbool(rdict.get('search_content', False)) 

 

    conn_str = request.registry.settings.get('sqlalchemy.url', False) 

    searcher = get_fulltext_handler(conn_str) 

 

    # check if we have a page count submitted 

    page = rdict.get('page', 0) 

    count = rdict.get('count', 10) 

 

    if 'username' in mdict: 

        with_user = True 

    else: 

        with_user = False 

 

    res_list = searcher.search(phrase, 

                               content=search_content, 

                               username=username if with_user else None, 

                               ct=count, 

                               page=page) 

 

    constructed_results = [] 

    for res in res_list: 

        return_obj = dict(res) 

        return_obj['tags'] = [dict(tag[1]) for tag in res.tags.items()] 

 

        # the hashed object is there as well, we need to pull the url and 

        # clicks from it as total_clicks 

        return_obj['url'] = res.hashed.url 

        return_obj['total_clicks'] = res.hashed.clicks 

 

        constructed_results.append(return_obj) 

 

    return { 

        'search_results': constructed_results, 

        'result_count': len(constructed_results), 

        'phrase': phrase, 

        'page': page, 

        'with_content': search_content, 

        'username': username, 

    } 

 

 

@view_config(route_name="api_tag_complete", renderer="json") 

@view_config(route_name="api_tag_complete_user", renderer="json") 

@api_auth('api_key', UserMgr.get, anon=True) 

def tag_complete(request): 

    """Complete a tag based on the given text 

 

    :@param tag: GET string, tag=sqlalchemy 

    :@param current: GET string of tags we already have python+database 

 

    """ 

    params = request.GET 

 

    if request.user: 

        username = request.user.username 

    else: 

        username = None 

 

    if 'current' in params and params['current'] != "": 

        current_tags = params['current'].split() 

    else: 

        current_tags = None 

 

    if 'tag' in params and params['tag']: 

        tag = params['tag'] 

 

        tags = TagMgr.complete(tag, 

                               current=current_tags, 

                               username=username) 

    else: 

        tags = [] 

 

    # reset this for the payload join operation 

    if current_tags is None: 

        current_tags = [] 

 

    return { 

        'current': ",".join(current_tags), 

        'tags': [t.name for t in tags] 

    } 

 

 

# USER ACCOUNT INFORMATION CALLS 

@view_config(route_name="api_user_account", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def account_info(request): 

    """Return the details of the user account specifed 

 

    expecting username in matchdict 

    We only return a subset of data. We're not sharing keys such as api_key, 

    password hash, etc. 

 

    """ 

    user = request.user 

 

    return user.safe_data() 

 

 

@view_config(route_name="api_user_account_update", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def account_update(request): 

    """Update the account information for a user 

 

    :params name: 

    :params email: 

 

    Callable by either a logged in user or the api key for mobile apps/etc 

 

    """ 

    params = request.params 

    json_body = request.json_body 

    user_acct = request.user 

 

    if 'name' in params and params['name'] is not None: 

        name = params.get('name') 

        user_acct.name = name 

 

    if 'name' in json_body and json_body['name'] is not None: 

        name = json_body.get('name') 

        user_acct.name = name 

 

    if 'email' in params and params['email'] is not None: 

        email = params.get('email') 

        user_acct.email = email 

 

    if 'email' in json_body and json_body['email'] is not None: 

        email = json_body.get('email') 

        user_acct.email = email 

 

    return user_acct.safe_data() 

 

 

@view_config(route_name="api_user_api_key", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def api_key(request): 

    """Return the currently logged in user's api key 

 

    This api call is available both on the website via a currently logged in 

    user and via a valid api key passed into the request. In this way we should 

    be able to add this to the mobile view with an ajax call as well as we do 

    into the account information on the main site. 

 

    """ 

    user_acct = request.user 

    return { 

        'api_key': user_acct.api_key, 

        'username': user_acct.username 

    } 

 

 

@view_config(route_name="api_user_reset_password", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def reset_password(request): 

    """Change a user's password from the current string 

 

    :params current_password: 

    :params new_password: 

 

    Callable by either a logged in user or the api key for mobile apps/etc 

 

    """ 

    params = request.params 

 

    # now also load the password info 

    current = params.get('current_password', None) 

    new = params.get('new_password', None) 

 

    # if we don't have any password info, try a json_body in case it's a json 

    #POST 

    if current is None and new is None: 

        params = request.json_body 

        current = params.get('current_password', None) 

        new = params.get('new_password', None) 

 

    user_acct = request.user 

 

    LOG.error("PASSWD") 

    LOG.error(current) 

    LOG.error(new) 

    if not UserMgr.acceptable_password(new): 

        request.response.status_int = 406 

        return { 

            'username': user_acct.username, 

            'error': "Come on, let's try a real password this time" 

        } 

 

    # before we change the password, let's verify it 

    if user_acct.validate_password(current): 

        # we're good to change it 

        user_acct.password = new 

        return { 

            'username': user_acct.username, 

            'message': "Password changed", 

        } 

    else: 

        request.response.status_int = 403 

        return { 

            'username': user_acct.username, 

            'error': "There was a typo somewhere. Please check your request" 

        } 

 

 

@view_config(route_name="api_user_suspend", renderer="json") 

def suspend_acct(request): 

    """Reset a user account to enable them to change their password""" 

    params = request.params 

    user = request.user 

 

    # we need to get the user from the email 

    email = params.get('email', None) 

 

    if email is None and hasattr(request, 'json_body'): 

        # try the json body 

        email = request.json_body.get('email', None) 

 

    if user is None and email is None: 

        request.response.status_int = 406 

        return { 

            'error': "Please submit an email address", 

        } 

 

    if user is None and email is not None: 

        user = UserMgr.get(email=email) 

 

    if user is None: 

        request.response.status_int = 404 

        return { 

            'error': "Please submit a valid address", 

            'email': email 

        } 

 

    # check if we've already gotten an activation for this user 

    if user.activation is not None: 

        request.response.status_int = 406 

        return { 

            'error': """You've already marked your account for reactivation. 

Please check your email for the reactivation link. Make sure to 

check your spam folder.""", 

            'username': user.username, 

        } 

 

    # mark them for reactivation 

    user.reactivate("FORGOTTEN") 

 

    # log it 

    AuthLog.reactivate(user.username) 

 

    # and then send an email notification 

    # @todo the email side of things 

    settings = request.registry.settings 

    msg = ReactivateMsg(user.email, 

                        "Activate your Bookie account", 

                        settings) 

 

    msg.send({ 

        'url': request.route_url( 

            'reset', 

            username=user.username, 

            reset_key=user.activation.code), 

        'username': user.username 

    }) 

 

    return { 

        'message': """Your account has been marked for reactivation. Please 

                    check your email for instructions to reset your 

                    password""", 

    } 

 

 

@view_config(route_name="api_user_suspend_remove", renderer="json") 

def account_activate(request): 

    """Reset a user after being suspended 

 

    :param username: required to know what user we're resetting 

    :param activation: code needed to activate 

    :param password: new password to use for the user 

 

    """ 

    params = request.params 

 

    username = params.get('username', None) 

    activation = params.get('code', None) 

    password = params.get('password', None) 

    new_username = params.get('new_username', None) 

 

    if username is None and activation is None and password is None: 

        # then try to get the same fields out of a json body 

        json_body = request.json_body 

        username = json_body.get('username', None) 

        activation = json_body.get('code', None) 

        password = json_body.get('password', None) 

        new_username = json_body.get('new_username', None) 

 

    if not UserMgr.acceptable_password(password): 

        request.response.status_int = 406 

        return { 

            'error': "Come on, pick a real password please", 

        } 

 

    res = ActivationMgr.activate_user(username, activation, password) 

 

    if res: 

        # success so respond nicely 

        AuthLog.reactivate(username, success=True, code=activation) 

 

        # if there's a new username and it's not the same as our current 

        # username, update it 

        if new_username and new_username != username: 

            try: 

                user = UserMgr.get(username=username) 

                user.username = new_username 

            except IntegrityError, exc: 

                request.response.status_int = 500 

                return { 

                    'error': 'There was an issue setting your new username', 

                    'exc': str(exc) 

                } 

 

        return { 

            'message': "Account activated, please log in.", 

            'username': username, 

        } 

    else: 

        AuthLog.reactivate(username, success=False, code=activation) 

        request.response.status_int = 500 

        return { 

            'error': "There was an issue attempting to activate this account.", 

        } 

 

 

@view_config(route_name="api_user_invite", renderer="json") 

@api_auth('api_key', UserMgr.get) 

def invite_user(request): 

    """Invite a new user into the system. 

 

    :param username: user that is requested we invite someone 

    :param email: email address of the new user 

 

    """ 

    params = request.params 

 

    email = params.get('email', None) 

    user = request.user 

 

    if not email: 

        # try to get it from the json body 

        email = request.json_body.get('email', None) 

 

    if not email: 

        # if still no email, I give up! 

        request.response.status_int = 406 

        return { 

            'username': user.username, 

            'error': "Please submit an email address" 

        } 

 

    # first see if the user is already in the system 

    exists = UserMgr.get(email=email) 

    if exists: 

        request.response.status_int = 406 

        return { 

            'username': exists.username, 

            'error': "This user is already a Bookie user!" 

        } 

 

    new_user = user.invite(email) 

    if new_user: 

        LOG.error(new_user.username) 

        # then this user is able to invite someone 

        # log it 

        AuthLog.reactivate(new_user.username) 

 

        # and then send an email notification 

        # @todo the email side of things 

        settings = request.registry.settings 

        msg = InvitationMsg(new_user.email, 

                            "Enable your Bookie account", 

                            settings) 

 

        msg.send( 

            request.route_url( 

                'reset', 

                username=new_user.username, 

                reset_key=new_user.activation.code)) 

        return { 

            'message': 'You have invited: ' + new_user.email 

        } 

    else: 

        # you have no invites 

        request.response.status_int = 406 

        return { 

            'username': user.username, 

            'error': "You have no invites left at this time." 

        } 

 

 

@view_config(route_name="api_admin_readable_todo", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def to_readable(request): 

    """Get a list of urls, hash_ids we need to readable parse""" 

    url_list = Bmark.query.outerjoin(Readable, Readable.bid == Bmark.bid).\ 

        join(Bmark.hashed).\ 

        options(contains_eager(Bmark.hashed)).\ 

        filter(Readable.imported == None).all() 

 

    def data(urls): 

        """Yield out the results with the url in the data streamed.""" 

        for url in urls: 

            d = dict(url) 

            d['url'] = url.hashed.url 

            yield d 

 

    return { 

        'urls': [u for u in data(url_list)] 

 

    } 

 

 

@view_config(route_name="api_admin_readable_reindex", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def readable_reindex(request): 

    """Force the fulltext index to rebuild 

 

    This loops through ALL bookmarks and might take a while to complete. 

 

    """ 

    tasks.reindex_fulltext_allbookmarks.delay() 

    return { 

        'success': True 

    } 

 

 

@view_config(route_name="api_admin_accounts_inactive", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def accounts_inactive(request): 

    """Return a list of the accounts that aren't activated.""" 

    user_list = UserMgr.get_list(active=False) 

    ret = { 

        'count': len(user_list), 

        'users': [dict(h) for h in user_list], 

    } 

    return ret 

 

 

@view_config(route_name="api_admin_accounts_invites", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def accounts_invites(request): 

    """Return a list of the accounts that aren't activated.""" 

    user_list = UserMgr.get_list() 

    ret = { 

        'users': [(u.username, u.invite_ct) for u in user_list], 

    } 

    return ret 

 

 

@view_config(route_name="api_admin_accounts_invites_add", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def accounts_invites_add(request): 

    """Set the number of invites a user has available. 

 

    :matchdict username: The user to give these invites to. 

    :matchdict count: The number of invites to give them. 

    """ 

    rdict = request.matchdict 

    username = rdict.get('username', None) 

    count = rdict.get('count', None) 

 

    if username is not None and count is not None: 

        user = UserMgr.get(username=username) 

 

        if user: 

            user.invite_ct = count 

            return dict(user) 

        else: 

            request.response.status_int = 404 

            ret = {'error': "Invalid user account."} 

            return ret 

    else: 

        request.response.status_int = 400 

        ret = {'error': "Bad request, missing parameters"} 

        return ret 

 

 

@view_config(route_name="api_admin_imports_list", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def import_list(request): 

    """Provide some import related data.""" 

    import_list = ImportQueueMgr.get_list() 

    ret = { 

        'count': len(import_list), 

        'imports': [dict(h) for h in import_list], 

    } 

    return ret 

 

 

@view_config(route_name="api_admin_imports_reset", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def import_reset(request): 

    """Reset an import to try again""" 

    rdict = request.matchdict 

    import_id = rdict.get('id', None) 

 

    if not id: 

        request.response.status_int = 400 

        ret = {'error': "Bad request, missing parameters"} 

        return ret 

 

    imp = ImportQueueMgr.get(int(import_id)) 

    imp.status = 0 

    tasks.importer_process.delay(imp.id) 

 

    ret = { 

        'import': dict(imp) 

    } 

    return ret 

 

 

@view_config(route_name="api_admin_users_list", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def user_list(request): 

    """Provide list of users in the system. 

 

    Supported Query params: order, limit 

    """ 

    params = request.params 

    order = params.get('order', None) 

    limit = params.get('limit', None) 

    user_list = UserMgr.get_list(order=order, limit=limit) 

    ret = { 

        'count': len(user_list), 

        'users': [dict(h) for h in user_list], 

    } 

    return ret 

 

 

@view_config(route_name="api_admin_new_user", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def new_user(request): 

    """Add a new user to the system manually.""" 

    rdict = request.params 

 

    u = User() 

 

    u.username = unicode(rdict.get('username')) 

    u.email = unicode(rdict.get('email')) 

    passwd = get_random_word(8) 

    u.password = passwd 

    u.activated = True 

    u.is_admin = False 

    u.api_key = User.gen_api_key() 

 

    try: 

        DBSession.add(u) 

        DBSession.flush() 

        # We need to return the password since the admin added the user 

        # manually.  This is only time we should have/give the original 

        # password. 

        ret = dict(u) 

        ret['random_pass'] = passwd 

        return ret 

 

    except IntegrityError, exc: 

        # We might try to add a user that already exists. 

        LOG.error(exc) 

        request.response.status_int = 400 

        return { 

            'error': 'Bad Request: User exists.', 

        } 

 

 

@view_config(route_name="api_admin_del_user", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def del_user(request): 

    """Remove a bad user from the system via the api. 

 

    For admin use only. 

 

    Removes all of a user's bookmarks before removing the user. 

 

    """ 

    mdict = request.matchdict 

 

    # Submit a username. 

    del_username = mdict.get('username', None) 

 

    if del_username is None: 

        LOG.error('No username to remove.') 

        request.response.status_int = 400 

        return { 

            'error': 'Bad Request: No username to remove.', 

        } 

 

    u = UserMgr.get(username=del_username) 

 

    if not u: 

        LOG.error('Username not found.') 

        request.response.status_int = 404 

        return { 

            'error': 'User not found.', 

        } 

 

    try: 

        # Delete all of the bmarks for this year. 

        Bmark.query.filter(Bmark.username == u.username).delete() 

        DBSession.delete(u) 

        return { 

            'success': True, 

            'message': 'Removed user: ' + del_username 

        } 

    except Exception, exc: 

        # There might be cascade issues or something that causes us to fail in 

        # removing. 

        LOG.error(exc) 

        request.response.status_int = 500 

        return { 

            'error': 'Bad Request: ' + str(exc) 

        } 

 

 

@view_config(route_name="api_admin_bmark_remove", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def admin_bmark_remove(request): 

    """Remove this bookmark from the system""" 

    rdict = request.matchdict 

    username = rdict.get('username') 

    hash_id = rdict.get('hash_id') 

 

    try: 

        bmark = BmarkMgr.get_by_hash(hash_id, 

                                     username=username) 

        print bmark 

        if bmark: 

            DBSession.delete(bmark) 

            return { 

                'message': "done", 

            } 

        else: 

            return { 

                'error': 'Bookmark not found.', 

            } 

 

    except NoResultFound: 

        request.response.status_code = 404 

        return { 

            'error': 'Bookmark with hash id {0} not found.'.format( 

                rdict['hash_id']) 

        } 

 

 

@view_config(route_name="api_admin_applog", renderer="json") 

@api_auth('api_key', UserMgr.get, admin_only=True) 

def admin_applog(request): 

    """Return applog data for admin use.""" 

    rdict = request.GET 

 

    # Support optional filter parameters 

    days = int(rdict.get('days', 1)) 

    status = rdict.get('status', None) 

    message = rdict.get('message', None) 

 

    log_list = AppLogMgr.find( 

        days=days, 

        message_filter=message, 

        status=status, 

    ) 

 

    ret = { 

        'count': len(log_list), 

        'logs': [dict(l) for l in log_list], 

    } 

    return ret