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

# -*- test-case-name: bloggerfs.tests.test_bloggerfs -*- 

 

# bloggerfs.py - blogger file system in userspace using FUSE 

# Copyright (C) 2010 Marco Giusti 

# 

# This library is free software; you can redistribute it and/or 

# modify it under the terms of the GNU Library General Public 

# License as published by the Free Software Foundation; either 

# version 2 of the License, or (at your option) any later version. 

# 

# This library 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 

# Library General Public License for more details. 

# 

# You should have received a copy of the GNU Library General Public 

# License along with this library; if not, write to the Free 

# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, 

# MA 02111-1307, USA 

 

 

# rfc3339.py -- Implementation of the majority of RFC 3339 for python. 

# Copyright (c) 2008, 2009, 2010 LShift Ltd. <query@lshift.net> 

 

 

# gdata - Python client library for Google data APIs 

# Copyright (C) 2009 Google 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. 

 

 

import sys 

import os 

import stat 

import errno 

import time 

import datetime 

import logging 

import inspect 

import functools 

import traceback 

try: 

    import cStringIO as StringIO 

except: 

    import StringIO as StringIO 

 

import fuse 

import gdata.blogger.client 

import atom.core 

import atom.data 

from zope.interface import interface, declarations, implements 

from zope.interface import Interface, Attribute 

from zope.interface.adapter import AdapterRegistry 

 

from . import rfc3339 

 

__author__ = 'Marco Giusti' 

__copyright__ = 'Copyright 2010, Marco Giusti' 

__license__ = 'LGPL' 

__version__ = '0.5' 

__email__ = 'marco.giusti@gmail.com' 

 

 

class NullHandler(logging.Handler): 

 

    def emit(self, record): 

        pass 

 

 

fuse.fuse_python_api = (0, 2) 

_logger = logging.getLogger('bloggerfs') 

_logger.addHandler(NullHandler()) 

_logger.setLevel(logging.WARNING) 

_debug = _logger.debug 

_info = _logger.info 

_warn = _logger.warn 

_error = _logger.error 

_critical = _logger.critical 

_exception = _logger.exception 

 

 

def _getmembers(obj, predicate=None): 

    """Return all members of an object as (name, value) pairs sorted by name. 

    Optionally, only return members that satisfy a given predicate.""" 

    if inspect.isclass(obj): 

        mro = (obj,) + inspect.getmro(obj) 

    else: 

        mro = (obj,) 

    results = [] 

    for key in dir(obj): 

        # First try to get the value via __dict__. Some descriptors don't 

        # like calling their __get__ (see bug #1785). 

        for base in mro: 

            if key in base.__dict__: 

                value = base.__dict__[key] 

                break 

        else: 

            value = getattr(obj, key) 

        if not predicate or predicate(value): 

            results.append((key, value)) 

    results.sort() 

    return results 

 

 

inspect.getmembers = _getmembers     # monkey patch inspect 

 

 

# Taken from Twisted 

 

globalRegistry = AdapterRegistry() 

ALLOW_DUPLICATES = False 

 

 

def _registered(registry, required, provided): 

    """ 

    Return the adapter factory for the given parameters in the given 

    registry, or None if there is not one. 

    """ 

    return registry.registered([required], provided) 

 

 

def registerAdapter(adapterFactory, origInterface, *interfaceClasses): 

    """Register an adapter class. 

 

    An adapter class is expected to implement the given interface, by 

    adapting instances implementing 'origInterface'. An adapter class's 

    __init__ method should accept one parameter, an instance implementing 

    'origInterface'. 

    """ 

    self = globalRegistry 

    assert interfaceClasses, "You need to pass an Interface" 

    global ALLOW_DUPLICATES 

 

    # deal with class->interface adapters: 

    if not isinstance(origInterface, interface.InterfaceClass): 

        origInterface = declarations.implementedBy(origInterface) 

 

    for interfaceClass in interfaceClasses: 

        factory = _registered(self, origInterface, interfaceClass) 

        if factory is not None and not ALLOW_DUPLICATES: 

            raise ValueError("an adapter (%s) was already registered." % 

                             (factory, )) 

    for interfaceClass in interfaceClasses: 

        self.register([origInterface], interfaceClass, '', adapterFactory) 

 

 

# add global adapter lookup hook for our newly created registry 

def _hook(iface, ob, lookup=globalRegistry.lookup1): 

    factory = lookup(declarations.providedBy(ob), iface) 

    if factory is None: 

        return None 

    else: 

        return factory(ob) 

interface.adapter_hooks.append(_hook) 

 

# End taken 

 

 

class INode(Interface): 

    """""" 

 

 

class IFileNode(INode): 

 

    def open(flags): 

        """File open operation""" 

 

    def read(size, offset): 

        """""" 

 

    def truncate(size): 

        """""" 

 

    def write(buf, size): 

        """""" 

 

    def release(flags): 

        """""" 

 

    def utime(times): 

        """""" 

 

    def rename(pathto): 

        """""" 

 

    def fsync(isfsyncfile): 

        """""" 

 

    def flush(): 

        """""" 

 

    def fgetattr(): 

        """Get file attributes. 

 

        Similar to stat().  The 'st_dev' and 'st_blksize' fields are 

        ignored.         The 'st_ino' field is ignored except if the 'use_ino' 

        mount option is given.""" 

 

    def lock(): 

        """""" 

 

    def create(mode, file_info): 

        """""" 

 

 

class IDirNode(INode): 

 

    def opendir(): 

        """""" 

 

    def readdir(): 

        """""" 

 

    def fsyncdir(): 

        """""" 

 

    def releasedir(): 

        """""" 

 

 

class IUpdated(Interface): 

 

    updated = Attribute('Modification time in seconds from epoch') 

 

 

class IPublished(Interface): 

 

    published = Attribute('Creation time in seconds from epoch') 

 

 

def getType(obj): 

    if isinstance(obj, DirNode): 

        return stat.S_IFDIR 

    return stat.S_IFREG 

 

 

def format_exception(): 

    return ''.join(traceback.format_exception_only(*sys.exc_info()[:2])) 

 

 

class DirEntry(fuse.Direntry): 

 

    def __eq__(self, other): 

        if other.__class__ != DirEntry: 

            return NotImplemented 

        if self.name != other.name or self.offset != other.offset or \ 

           self.type != other.type or self.ino != other.ino: 

            return False 

        return True 

 

    def __ne__(self, other): 

        return not self.__eq__(other) 

 

    def __repr__(self): 

        type = self.type == stat.S_IFREG and 'file' or 'dir' 

        return '<bloggerfs.DirEntry name="%s", type="%s">' % (self.name, type) 

 

 

def updatedFactory(node): 

    return IUpdated(node.parent) 

 

registerAdapter(updatedFactory, INode, IUpdated) 

 

 

def publishedFactory(node): 

    return IPublished(node.parent) 

 

registerAdapter(publishedFactory, INode, IPublished) 

 

 

class Node(object): 

    implements(INode) 

 

    def __init__(self, original, parent, client): 

        self.original = original 

        self.parent = parent 

        self.client = client 

 

    @property 

    def mtime(self): 

        try: 

            return IUpdated(self).updated 

        except TypeError: 

            return 0 

 

    @property 

    def ctime(self): 

        try: 

            return IPublished(self).published 

        except TypeError: 

            return 0 

 

    def locate(self, path): 

        raise NotImplementedError('Locate method not implemented') 

 

    truncate = release = open = lambda *a: 0 

 

 

class FileNode(Node): 

    implements(IFileNode) 

 

    mode = 0440 

 

    def locate(self, path): 

        assert path == [] 

        return self 

 

    @property 

    def text(self): 

        return self.original 

 

    def getattr(self): 

        size = len(self.text) 

        st = fuse.Stat(st_mode=stat.S_IFREG | self.mode, st_nlink=1, 

                       st_uid=os.getuid(), st_gid=os.getgid(), st_size=size, 

                       st_ctime=self.ctime, st_mtime=self.mtime) 

        return st 

 

    def read(self, size, offset): 

        return self.text[offset:offset+size] 

 

    def write(self, buf, offset): 

        raise IOError(errno.EACCES, 'Permission denied') 

 

registerAdapter(FileNode, str, IFileNode) 

 

 

class TextNode(FileNode): 

 

    @property 

    def text(self): 

        if self.original.text is not None: 

            return self.original.text 

        return '' 

 

registerAdapter(TextNode, atom.data.Text, IFileNode) 

registerAdapter(TextNode, atom.data.Date, IFileNode) 

registerAdapter(TextNode, atom.data.Id, IFileNode) 

registerAdapter(TextNode, atom.data.Draft, IFileNode) 

registerAdapter(TextNode, atom.data.Name, IFileNode) 

registerAdapter(TextNode, atom.data.Email, IFileNode) 

registerAdapter(TextNode, atom.data.Uri, IFileNode) 

 

 

class DirNode(Node): 

    implements(IDirNode) 

 

    mode = 0550 

    _children = None 

 

    def getChildren(self): 

        return {} 

 

    @property 

    def children(self): 

        if self._children is None: 

            self._children = self.getChildren() 

        return self._children 

 

    def getChild(self, k): 

        if k in self.children: 

            return self.children[k] 

        raise IOError(errno.ENOENT, 'No such file or directory') 

 

    def addChild(self, k, v): 

        self.children[k] = v 

 

    def deleteChild(self, k): 

        if k not in self.children: 

            raise IOError(errno.ENOENT, 'No such file or directory') 

        del self.children[k] 

 

    def buildChildNode(self, obj, lookup=globalRegistry.lookup1): 

        factory = lookup(declarations.providedBy(obj), INode) 

        if factory is not None: 

            return factory(obj, self, self.client) 

        return None 

 

    def locate(self, path): 

        if path == []: 

            return self 

        name = path.pop(0) 

        child = self.getChild(name) 

        return child.locate(path) 

 

    def readdir(self, offset): 

        assert offset == 0, 'readdir, offset != 0' 

        yield DirEntry('.', type=stat.S_IFDIR) 

        yield DirEntry('..', type=stat.S_IFDIR) 

        for name, node in self.children.items(): 

            yield DirEntry(name, type=getType(node)) 

 

    def getattr(self): 

        st = fuse.Stat(st_mode=stat.S_IFDIR | self.mode, st_nlink=2, 

                       st_uid=os.geteuid(), st_gid=os.getegid(), st_size=4096, 

                       st_ctime=self.ctime, st_mtime=self.mtime) 

        return st 

 

    def rmdir(self): 

        raise IOError(errno.EACCES, 'Permission denied') 

 

 

class TimeOutMixin(object): 

 

    def __init__(self, original, parent, client, seconds=300): 

        super(TimeOutMixin, self).__init__(original, parent, client) 

        self._tick = datetime.datetime.now() 

        self.seconds = seconds 

        self.delta = datetime.timedelta(seconds=seconds) 

 

    @property 

    def children(self): 

        now = self._tick 

        if self.seconds is None: 

            shouldUpdate = False 

        else: 

            now = datetime.datetime.now() 

            expire = datetime.timedelta(seconds=self.seconds) 

            shouldUpdate = now - self._tick > expire 

        if self._children is None or shouldUpdate: 

            self._children = self.getChildren() 

            self._tick = now 

        return self._children 

 

 

class ListNode(DirNode): 

 

    def getChildren(self): 

        return dict((str(i), self.buildChildNode(el)) 

                    for i, el in enumerate(self.original)) 

 

registerAdapter(ListNode, list, IDirNode) 

 

 

class DictNode(DirNode): 

 

    def getChildren(self): 

        return dict((str(k), self.buildChildNode(v)) 

                    for k, v in self.original.iteritems()) 

 

registerAdapter(DictNode, dict, IDirNode) 

 

 

class ElementNode(DirNode): 

 

    def getChildren(self): 

        children = {} 

        for name, member_type in self.original._members: 

            if isinstance(member_type, tuple): 

                continue 

 

            element = getattr(self.original, name) 

            if element is not None: 

                children[name] = self.buildChildNode(element) 

        if self.original.text: 

            children['text'] = self.buildChildNode(self.original.text) 

        return children 

 

registerAdapter(ElementNode, atom.core.XmlElement, IDirNode) 

 

 

# class LabelNode(ElementNode): 

 

#     def rmdir(self): 

#         post = self.getParent(IPost, self.parent) 

#         if post is not None: 

#             post.deleteLabel(self) 

#             return 0 

#         raise IOError(errno.EACCES, 'Permission denied') 

 

 

class FeedEntryNode(ElementNode): 

    implements(IUpdated) 

 

    stale = True 

    _updated = None 

 

    @property 

    def updated(self): 

        if self._updated is None: 

            if self.original.updated: 

                try: 

                    updated = self.original.updated.text 

                    updated = rfc3339.parse_datetime(updated) 

                    self._updated = int(time.mktime(updated.timetuple())) 

                except: 

                    _exception('') 

                    self._updated = int(time.time()) 

            else: 

                self._updated = int(time.time()) 

        return self._updated 

 

    @property 

    def children(self): 

        if self.stale: 

            self.update() 

            self.stale = False 

            self._children = None 

        if self._children is None: 

            self._children = self.getChildren() 

        return self._children 

 

    def update(self): 

        raise NotImplementedError('%s.update' % self.__class__) 

 

 

class EntryNode(FeedEntryNode): 

    implements(IPublished) 

 

    _published = None 

 

    @property 

    def published(self): 

        if self._published is None: 

            if self.original.published: 

                try: 

                    published = self.original.published.text 

                    published = rfc3339.parse_datetime(published) 

                    self._published = int(time.mktime(published.timetuple())) 

                except: 

                    _exception('') 

                    self._published = self.mtime 

            else: 

                self._published = self.mtime 

        return self._published 

 

    def update(self): 

        o = self.original 

        try: 

            newo = self.client.get_entry(o.get_self_link().href, etag=o.etag, 

                                         desired_class=o.__class__) 

            self.original = newo 

            if self.stale: 

                self.stale = False 

        except gdata.client.NotModified: 

            pass 

        except gdata.client.RequestError: 

            _exception('') 

 

registerAdapter(EntryNode, atom.data.Entry, IDirNode) 

 

 

class BloggerEntryNode(EntryNode): 

 

    def getBlogId(self): 

        return self.original.get_blog_id() 

 

    def getBlogName(self): 

        return self.original.get_blog_name() 

 

registerAdapter(BloggerEntryNode, gdata.blogger.data.BloggerEntry, IDirNode) 

 

 

class CommentNode(BloggerEntryNode): 

 

    def getCommentId(self): 

        return self.original.get_comment_id() 

 

    def rmdir(self): 

        self.client.delete(self.original) 

        self.parent.deleteChild(self.getCommentId()) 

 

registerAdapter(CommentNode, gdata.blogger.data.Comment, IFileNode) 

 

 

class WriteOnlyMixin(object): 

 

    _sio = None 

 

    def open(self, flags): 

        if flags & 3 != os.O_WRONLY: 

            raise IOError(errno.EINVAL, 'Write only file') 

        self._sio = StringIO.StringIO() 

 

    def read(self, size, offset): 

        raise IOError(errno.EINVAL, 'Write only file') 

 

    def flush(self): 

        try: 

            self._flush() 

        except gdata.client.RequestError, e: 

            _exception('') 

            raise IOError(errno.EIO, e.reason) 

        except IOError: 

            raise 

        except Exception, e: 

            _exception('') 

            error = format_exception() 

            raise IOError(errno.EINVAL, error) 

 

    def _flush(self): 

        raise NotImplementedError() 

 

    def release(self, flags): 

        self._sio.close() 

        self._sio = None 

 

    def write(self, buf, offset): 

        _debug('writing %d bytes at %d' % (len(buf), offset)) 

        self._sio.seek(offset) 

        self._sio.write(buf) 

        return len(buf) 

 

 

class PostNode(TimeOutMixin, BloggerEntryNode): 

 

    def getChildren(self): 

        children = BloggerEntryNode.getChildren(self) 

        try: 

            feed = self.client.get_post_comments(self.getBlogId(), self.getPostId()) 

            comments = dict((e.get_comment_id(), e) for e in feed.entry) 

            children['comments'] = self.buildChildNode(comments) 

 

            class AddLabelNode(WriteOnlyMixin, FileNode): 

                def _flush(_self): 

                    category = self.children['category'] 

                    buf = _self._sio.getvalue() 

                    all_lbls = [buf] 

                    for lbl in category.original: 

                        all_lbls.append(lbl.term) 

                    if len(','.join(all_lbls)) > 200: 

                        raise IOError(errno.EMSGSIZE, 'The combined length of ' 

                                      'all the labels must be at most 200 ' 

                                      'characters') 

                    self.original.add_label(buf) 

                    self.stale = True 

 

            def addCommentFactory(_type): 

                blogId = self.getBlogId() 

                postId = self.getPostId() 

                class AddCommentNode(WriteOnlyMixin, FileNode): 

                    def _flush(_self): 

                        self.client.add_comment(blogId, postId, 

                                           _self._sio.getvalue(), 

                                           body_type=_type) 

                        self.stale = True 

                return AddCommentNode 

 

            children['add_label'] = AddLabelNode('', self, self.client) 

            add_comment = addCommentFactory('text')('', self, self.client) 

            children['add_comment'] = add_comment 

            add_html_comment = addCommentFactory('html')('', self, self.client) 

            children['add_html_comment'] = add_html_comment 

        except gdata.client.RequestError: 

            _exception('') 

        return children 

 

    def getPostId(self): 

        return self.original.get_post_id() 

 

    # def deleteLabel(self, labelNode): 

    #     if 'category' in self.children: 

    #         cat = self.getChild('category') 

    #     if not self.dirty: 

    #         self.dirty = True 

 

    def rmdir(self): 

        self.client.delete(self.original) 

        self.parent.deleteChild(self.getPostId()) 

 

registerAdapter(PostNode, gdata.blogger.data.BlogPost, IDirNode) 

 

 

class AddPostNode(WriteOnlyMixin, FileNode): 

 

    class BlogFeed: 

        klass = gdata.blogger.data.BlogFeed 

        @staticmethod 

        def getEntry(feed): 

            if len(feed.entry) > 0: 

                return feed.entry[0] 

 

    class BlogPost: 

        klass = gdata.blogger.data.BlogPost 

        @staticmethod 

        def getEntry(entry): 

            return entry 

 

    def getTargets(self): 

        return self.BlogFeed, self.BlogPost 

 

    def _flush(self): 

        buf = self._sio.getvalue() 

        if len(buf) == 0: 

            return 

        _debug('Flushing %d bytes' % len(buf)) 

        for target in self.getTargets(): 

            element = atom.core.parse(buf, target.klass, 2) 

            if element is None: 

                continue 

            entry = target.getEntry(element) 

            if entry is not None: 

                post = self.client.post(entry, gdata.blogger.client.BLOG_POST_URL % 

                                        self.parent.getBlogId(), 

                                        desired_class=gdata.blogger.data.BlogPost) 

                self.parent.addPost(post) 

                return 

        raise IOError(errno.EINVAL, 'Cannot parse xml to a valid class') 

 

 

class BlogNode(TimeOutMixin, BloggerEntryNode): 

 

    @property 

    def id(self): 

        return self.original.get_blog_id() 

 

    def getChildren(self): 

        children = BloggerEntryNode.getChildren(self) 

        children['add_post'] = AddPostNode('', self, self.client) 

        try: 

            feed = self.client.get_posts(self.getBlogId()) 

            posts = dict((e.get_post_id(), e) for e in feed.entry) 

            children['posts'] = self.buildChildNode(posts) 

        except gdata.client.RequestError: 

            _exception('') 

        return children 

 

    def addPost(self, post): 

        self.children['posts'].addChild(post.get_post_id(), 

                                        self.buildChildNode(post)) 

 

    def update(self): 

        _warn('Not implemented yet') 

 

registerAdapter(BlogNode, gdata.blogger.data.Blog, IDirNode) 

 

 

class AccountNode(BloggerEntryNode): 

    implements(IPublished) 

 

    _original = None 

    published = time.time() 

 

    def __init__(self, client): 

        self.client = client 

 

    def _get_original(self): 

        if self._original is None: 

            try: 

                self._original = self.client.get_blogs() 

            except gdata.client.RequestError, e: 

                _exception('') 

                raise IOError(errno.EIO, e.reason) 

        return self._original 

    def _set_original(self, val): 

        self._original = val 

    original = property(_get_original, _set_original) 

 

    @property 

    def parent(self): 

        return self 

 

    def getChildren(self): 

        return dict((e.get_blog_id(), self.buildChildNode(e)) 

                    for e in self.original.entry) 

 

    # def update(self): 

    #     try: 

    #         self._original = client.get_blogs() 

    #     except gdata.client.RequestError, e: 

    #         _exception('') 

    #         raise IOError(errno.EIO, e.reason) 

 

    def update(self): 

        _warn('Not implemented yet') 

 

    # def getParent(self, iface): 

    #     if iface.providedBy(self): 

    #         return self 

    #     return None 

 

registerAdapter(AccountNode, gdata.blogger.data.BlogFeed, IDirNode) 

 

 

def catchException(f): 

    @functools.wraps 

    def wrapper(*args, **kwds): 

        try: 

            return f(*args, **kwds) 

        except: 

            _exception('Error in fuse api') 

            raise 

    return wrapper 

 

 

def splitpath(path): 

    return (path.split('/')[1:], [])[path == '/'] 

 

 

def callNodeMethod(name, doc=''): 

    def call(self, path, *args, **kwds): 

        try: 

            parts = splitpath(path) 

            node = self.account.locate(parts) 

            # if node.stale: 

            #     node.update() 

            func = getattr(node, name, None) 

            if func is None: 

                raise IOError(errno.ENOSYS, 'Function %s not ' 

                              'implemented' % name) 

            return func(*args, **kwds) 

        except: 

            _exception('Error in %s' % name) 

            raise 

    call.__name__ = name 

    call.__doc__ = doc 

    return call 

 

 

class BloggerFS(fuse.Fuse): 

 

    def main(self): 

        if self.parser.fuse_args.mount_expected(): 

            options = self.cmdline[0] 

            if options.debug: 

                _logger.setLevel(logging.DEBUG) 

            if options.syslog: 

                from logging import handlers 

                handler = handlers.SysLogHandler() 

            elif options.logfile: 

                from logging import handlers 

                handler = handlers.FileHandler(options.logfile) 

            elif options.debug: 

                handler = logging.StreamHandler() 

            formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] ' 

                                          '[%(funcName)s]  %(message)s') 

            handler.setFormatter(formatter) 

            _logger.addHandler(handler) 

 

            client = gdata.blogger.client.BloggerClient() 

            self.account = AccountNode(client) 

 

            if not options.email: 

                from gdata.sample_util import authorize_client 

                authorize_client(client, service='blogger', 

                                 source='bloggerfs', 

                                 scopes=['http://www.blogger.com/feeds/']) 

            else: 

                email = options.email 

                if not options.password: 

                    import getpass 

                    password = getpass.getpass() 

                else: 

                    password = options.password 

                client.client_login(email, password, source='bloggerfs', 

                                    service='blogger') 

        fuse.Fuse.main(self) 

 

    # files 

    open = callNodeMethod('open') 

    read = callNodeMethod('read') 

    write = callNodeMethod('write') 

    truncate = callNodeMethod('truncate') 

    flush = callNodeMethod('flush') 

    release = callNodeMethod('release') 

    # rename = callNodeMethod('rename') 

    # fsync = callNodeMethod('fsync') 

 

    # directories 

    readdir = callNodeMethod('readdir') 

    # rmdir = callNodeMethod('rmdir') 

    # mkdir = callNodeMethod('mkdir') 

    # opendir = callNodeMethod('opendir') 

    # releasedir = callNodeMethod('releasedir') 

    # fsyncdir = callNodeMethod('fsyncdir') 

 

    # misc 

    getattr = callNodeMethod('getattr') 

    # setattr = callNodeMethod('setattr') 

    # setxattr = callNodeMethod('setxattr') 

    # fgetattr = callNodeMethod('fgetattr') 

    # getxattr = callNodeMethod('getxattr') 

    # listxattr = callNodeMethod('listxattr') 

    # setxattr = callNodeMethod('setxattr') 

    # removexattr = callNodeMethod('removexattr') 

    # statfs = callNodeMethod('statfs') 

    # utime = callNodeMethod('utime') 

    # utimens = callNodeMethod('utimens') 

    # mknod = callNodeMethod('mknod') 

    # chmod = callNodeMethod('chmod') 

    # chown = callNodeMethod('chown') 

    # create = callNodeMethod('create') 

    # ftruncate = callNodeMethod('ftruncate') 

    # access = callNodeMethod('access') 

    # lock = callNodeMethod('lock') 

    # utimens = callNodeMethod('utimens') 

    # bmap = callNodeMethod('bmap') 

 

    # links 

    # readlink = callNodeMethod('readlink') 

    # unlink = callNodeMethod('unlink') 

    # symlink = callNodeMethod('symlink') 

    # link = callNodeMethod('link') 

 

 

def main(argv=None): 

    if argv is None: 

        import sys 

        argv = sys.argv[1:] 

 

    server = BloggerFS() 

    server.parser.add_option('-e', '--email', help='Google account email') 

    server.parser.add_option('-p', '--password', 

                             help='Google account password') 

    server.parser.add_option('-b', '--debug', help='Show debugging info', 

                             action='store_true') 

    server.parser.add_option('--syslog', action='store_true', 

                             help='Log messages to syslog') 

    server.parser.add_option('-l', '--logfile', help='Log messages to file') 

    server.parse(args=argv, errex=1) 

    server.main() 

 

 

if __name__ == '__main__': 

    main()