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

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

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

 

# Licensed under the MIT license 

# http://opensource.org/licenses/mit-license.php 

 

# Copyright 2006, Frank Scholz <coherence@beebits.net> 

""" 

FSStore - Filesystem media server 

 

FSStore exposes media files found in the directory trees defined by 

the 'content' configuration entry. 

 

The first ".jpg" or ".png" file found inside a media directory is 

served as a cover image. 

 

The plugin is configured with: 

 

<plugin active="yes"> 

  <!-- The plugin identifier, mandatory --> 

  <backend>FSStore</backend> 

  <!-- A comma-separated list of path containing the medias to serve --> 

  <content>/media/path1,/media/path2</content> 

  <!-- The avertized media server name, default: "my media" --> 

  <name>my media</name> 

  <!-- The highest UPnP version this 

  media server should support, default: 2 --> 

  <version>2</version> 

  <!-- A unique identifier used to reference the media server, autogenerated 

  if not set explicitely. In this case, some control points might memorize it 

  between runs and display the same media server more than once. 

  --> 

  <uuid>2f7f4096-cba3-4390-be7d-d1d07106a6f4</uuid> 

</plugin> 

""" 

import glob 

import mimetypes 

import os 

import re 

import shutil 

import stat 

import tempfile 

import traceback 

from datetime import datetime 

from functools import partial 

from urllib.parse import quote 

 

mimetypes.init() 

mimetypes.add_type('audio/x-m4a', '.m4a') 

mimetypes.add_type('audio/x-musepack', '.mpc') 

mimetypes.add_type('audio/x-wavpack', '.wv') 

mimetypes.add_type('video/mp4', '.mp4') 

mimetypes.add_type('video/mpegts', '.ts') 

mimetypes.add_type('video/divx', '.divx') 

mimetypes.add_type('video/divx', '.avi') 

mimetypes.add_type('video/x-matroska', '.mkv') 

 

from urllib.parse import urlsplit 

 

from twisted.python.filepath import FilePath 

from twisted.python import failure 

 

from coherence.upnp.core.DIDLLite import classChooser, Container, Resource 

from coherence.upnp.core.DIDLLite import DIDLElement 

from coherence.upnp.core.DIDLLite import simple_dlna_tags 

from coherence.upnp.core.soap_service import errorCode 

 

from coherence.upnp.core import utils 

 

try: 

    from twisted.internet.inotify import ( 

        INotify, IN_CREATE, IN_DELETE, IN_MOVED_FROM, IN_MOVED_TO, 

        IN_ISDIR, IN_CHANGED) 

except Exception as msg: 

    INotify = None 

    no_inotify_reason = msg 

 

from coherence.extern.xdg import xdg_content 

 

import coherence.extern.louie as louie 

 

from coherence.backend import BackendItem, BackendStore 

 

# Sorting helpers 

NUMS = re.compile('([0-9]+)') 

 

 

def _natural_key(s): 

    # strip the spaces 

    s = s.get_name().strip() 

    return [part.isdigit() and int(part) or part.lower() for part in 

            NUMS.split(s)] 

 

 

class NoThumbnailFound(Exception): 

    """no thumbnail found""" 

 

 

def _find_thumbnail(filename, thumbnail_folder='.thumbs'): 

    """ looks for a thumbnail file of the same basename 

        in a folder named '.thumbs' relative to the file 

 

        returns the filename of the thumb, its mimetype and 

        the correspondig DLNA PN string or throws an Exception otherwise 

    """ 

    name, ext = os.path.splitext(os.path.basename(filename)) 

    pattern = os.path.join(os.path.dirname(filename), thumbnail_folder, 

                           name + '.*') 

    for f in glob.glob(pattern): 

        mimetype, _ = mimetypes.guess_type(f, strict=False) 

        if mimetype in ('image/jpeg', 'image/png'): 

            if mimetype == 'image/jpeg': 

                dlna_pn = 'DLNA.ORG_PN=JPEG_TN' 

            else: 

                dlna_pn = 'DLNA.ORG_PN=PNG_TN' 

            return os.path.abspath(f), mimetype, dlna_pn 

    else: 

        raise NoThumbnailFound() 

 

 

class FSItem(BackendItem): 

    logCategory = 'fs_item' 

 

    def __init__(self, object_id, parent, path, mimetype, urlbase, UPnPClass, 

                 update=False, store=None): 

        BackendItem.__init__(self) 

        self.id = object_id 

        self.parent = parent 

        if parent: 

            parent.add_child(self, update=update) 

        if mimetype == 'root': 

            self.location = str(path) 

        else: 

            if mimetype == 'item' and path is None: 

                path = os.path.join(parent.get_realpath(), str(self.id)) 

            # self.location = FilePath(unicode(path)) 

            self.location = FilePath(path) 

        self.mimetype = mimetype 

        if urlbase[-1] != '/': 

            urlbase += '/' 

        self.url = urlbase + str(self.id) 

 

        self.store = store 

 

        if parent is None: 

            parent_id = -1 

        else: 

            parent_id = parent.get_id() 

 

        self.item = UPnPClass(object_id, parent_id, self.get_name()) 

        if isinstance(self.item, Container): 

            self.item.childCount = 0 

        self.child_count = 0 

        self.children = [] 

        self.sorted = False 

        self.caption = None 

 

        if mimetype in ['directory', 'root']: 

            self.update_id = 0 

            self.get_url = lambda: self.url 

            # self.item.searchable = True 

            # self.item.searchClass = 'object' 

            if (isinstance(self.location, FilePath) and 

                    self.location.isdir() is True): 

                self.check_for_cover_art() 

                if getattr(self, 'cover', None): 

                    _, ext = os.path.splitext(self.cover) 

                    """ add the cover image extension to help clients 

                        not reacting on the mimetype """ 

                    self.item.albumArtURI = \ 

                        ''.join((urlbase, str(self.id), '?cover', str(ext))) 

        else: 

            self.get_url = lambda: self.url 

 

            if self.mimetype.startswith('audio/'): 

                if getattr(parent, 'cover', None): 

                    _, ext = os.path.splitext(parent.cover) 

                    """ add the cover image extension to help clients 

                        not reacting on the mimetype """ 

                    self.item.albumArtURI = \ 

                        ''.join((urlbase, str(self.id), '?cover', ext)) 

 

            _, host_port, _, _, _ = urlsplit(urlbase) 

            if host_port.find(':') != -1: 

                host, port = tuple(host_port.split(':')) 

            else: 

                host = host_port 

 

            try: 

                size = self.location.getsize() 

            except Exception: 

                size = 0 

 

            if (self.store.server and 

                    self.store.server.coherence.config.get('transcoding', 

                                                           'no') == 'yes'): 

                if self.mimetype in ('application/ogg', 'audio/ogg', 

                                     'audio/x-wav', 

                                     'audio/x-m4a', 

                                     'application/x-flac'): 

                    new_res = Resource(self.url + '/transcoded.mp3', 

                                       'http-get:*:%s:*' % 'audio/mpeg') 

                    new_res.size = None 

                    # self.item.res.append(new_res) 

 

            if mimetype != 'item': 

                res = Resource( 

                    'file://' + quote( 

                        self.get_path(), 

                        encoding='utf-8'), 

                    'internal:%s:%s:*' % (host, self.mimetype)) 

                res.size = size 

                self.item.res.append(res) 

 

            if mimetype != 'item': 

                res = Resource(self.url, 'http-get:*:%s:*' % self.mimetype) 

            else: 

                res = Resource(self.url, 'http-get:*:*:*') 

 

            res.size = size 

            self.item.res.append(res) 

 

            """ if this item is of type audio and we want to add a transcoding 

                rule for it, this is the way to do it: 

 

                create a new Resource object, at least a 'http-get' 

                and maybe an 'internal' one too 

 

                for transcoding to wav this looks like that 

 

                res = Resource( 

                    url_for_transcoded audio, 

                    'http-get:*:audio/x-wav:%s'% ';'.join( 

                        ['DLNA.ORG_PN=JPEG_TN']+simple_dlna_tags)) 

                res.size = None 

                self.item.res.append(res) 

            """ 

 

            if (self.store.server and 

                    self.store.server.coherence.config.get( 

                        'transcoding', 'no') == 'yes'): 

                if self.mimetype in ('audio/mpeg', 

                                     'application/ogg', 'audio/ogg', 

                                     'audio/x-wav', 

                                     'audio/x-m4a', 

                                     'audio/flac', 

                                     'application/x-flac'): 

                    dlna_pn = 'DLNA.ORG_PN=LPCM' 

                    dlna_tags = simple_dlna_tags[:] 

                    # dlna_tags[1] = 'DLNA.ORG_OP=00' 

                    dlna_tags[2] = 'DLNA.ORG_CI=1' 

                    new_res = Resource( 

                        self.url + '?transcoded=lpcm', 

                        'http-get:*:%s:%s' % ( 

                            'audio/L16;rate=44100;channels=2', 

                            ';'.join([dlna_pn] + dlna_tags))) 

                    new_res.size = None 

                    # self.item.res.append(new_res) 

 

                    if self.mimetype != 'audio/mpeg': 

                        new_res = Resource(self.url + '?transcoded=mp3', 

                                           'http-get:*:%s:*' % 'audio/mpeg') 

                        new_res.size = None 

                        # self.item.res.append(new_res) 

 

            """ if this item is an image and we want to add a thumbnail for it 

                we have to follow these rules: 

 

                create a new Resource object, at least a 'http-get' 

                and maybe an 'internal' one too 

 

                for an JPG this looks like that 

 

                res = Resource(url_for_thumbnail, 

                        'http-get:*:image/jpg:%s'% ';'.join( 

                        ['DLNA.ORG_PN=JPEG_TN']+simple_dlna_tags)) 

                res.size = size_of_thumbnail 

                self.item.res.append(res) 

 

                and for a PNG the Resource creation is like that 

 

                res = Resource(url_for_thumbnail, 

                        'http-get:*:image/png:%s'% ';'.join( 

                        simple_dlna_tags+['DLNA.ORG_PN=PNG_TN'])) 

 

                if not hasattr(self.item, 'attachments'): 

                    self.item.attachments = {} 

                self.item.attachments[key] = utils.StaticFile( 

                filename_of_thumbnail) 

            """ 

 

            if (self.mimetype in ('image/jpeg', 'image/png') or 

                    self.mimetype.startswith('video/')): 

                try: 

                    filename, mimetype, dlna_pn = _find_thumbnail( 

                        self.get_path()) 

                except NoThumbnailFound: 

                    pass 

                except Exception: 

                    self.warning(traceback.format_exc()) 

                else: 

                    dlna_tags = simple_dlna_tags[:] 

                    dlna_tags[ 

                        3] = 'DLNA.ORG_FLAGS=00f00000000000000000000000000000' 

 

                    hash_from_path = str(id(filename)) 

                    new_res = Resource( 

                        self.url + '?attachment=' + hash_from_path, 

                        'http-get:*:%s:%s' % ( 

                            mimetype, ';'.join([dlna_pn] + dlna_tags))) 

                    new_res.size = os.path.getsize(filename) 

                    self.item.res.append(new_res) 

                    if not hasattr(self.item, 'attachments'): 

                        self.item.attachments = {} 

                    self.item.attachments[hash_from_path] = utils.StaticFile( 

                        filename) 

 

            if self.mimetype.startswith('video/'): 

                # check for a subtitles file 

                caption, _ = os.path.splitext(self.get_path()) 

                caption = caption + '.srt' 

                if os.path.exists(caption): 

                    hash_from_path = str(id(caption)) 

                    mimetype = 'smi/caption' 

                    new_res = Resource( 

                        self.url + '?attachment=' + hash_from_path, 

                        'http-get:*:%s:%s' % (mimetype, '*')) 

                    new_res.size = os.path.getsize(caption) 

                    self.caption = new_res.data 

                    self.item.res.append(new_res) 

                    if not hasattr(self.item, 'attachments'): 

                        self.item.attachments = {} 

                    self.item.attachments[hash_from_path] = utils.StaticFile( 

                        caption) 

 

            try: 

                # FIXME: getmtime is deprecated in Twisted 2.6 

                self.item.date = datetime.fromtimestamp( 

                    self.location.getmtime()) 

            except Exception: 

                self.item.date = None 

 

    def rebuild(self, urlbase): 

        # print "rebuild", self.mimetype 

        if self.mimetype != 'item': 

            return 

        # print "rebuild for", self.get_path() 

        mimetype, _ = mimetypes.guess_type(self.get_path(), strict=False) 

        if mimetype is None: 

            return 

        self.mimetype = mimetype 

        # print "rebuild", self.mimetype 

        UPnPClass = classChooser(self.mimetype) 

        self.item = UPnPClass(self.id, self.parent.id, self.get_name()) 

        if getattr(self.parent, 'cover', None): 

            _, ext = os.path.splitext(self.parent.cover) 

            """ add the cover image extension to help clients not reacting on 

                the mimetype """ 

            self.item.albumArtURI = ''.join( 

                (urlbase, str(self.id), '?cover', ext)) 

 

        _, host_port, _, _, _ = urlsplit(urlbase) 

        if host_port.find(':') != -1: 

            host, port = tuple(host_port.split(':')) 

        else: 

            host = host_port 

 

        res = Resource( 

            'file://' + quote( 

                self.get_path()), 

            'internal:%s:%s:*' % (host, self.mimetype)) 

        try: 

            res.size = self.location.getsize() 

        except Exception: 

            res.size = 0 

        self.item.res.append(res) 

        res = Resource(self.url, 'http-get:*:%s:*' % self.mimetype) 

 

        try: 

            res.size = self.location.getsize() 

        except Exception: 

            res.size = 0 

        self.item.res.append(res) 

 

        try: 

            # FIXME: getmtime is deprecated in Twisted 2.6 

            self.item.date = datetime.fromtimestamp(self.location.getmtime()) 

        except Exception: 

            self.item.date = None 

 

        self.parent.update_id += 1 

 

    def check_for_cover_art(self): 

        """ let's try to find in the current directory some jpg file, 

            or png if the jpg search fails, and take the first one 

            that comes around 

        """ 

        try: 

            jpgs = [i.path for i in self.location.children() if 

                    i.splitext()[1] in ('.jpg', '.JPG')] 

            try: 

                self.cover = jpgs[0] 

            except IndexError: 

                pngs = [i.path for i in self.location.children() if 

                        i.splitext()[1] in ('.png', '.PNG')] 

                try: 

                    self.cover = pngs[0] 

                except IndexError: 

                    return 

        except UnicodeDecodeError: 

            self.warning( 

                "UnicodeDecodeError - " 

                "there is something wrong with a file located in %r", 

                self.location.path) 

 

    def remove(self): 

        # print "FSItem remove", self.id, self.get_name(), self.parent 

        if self.parent: 

            self.parent.remove_child(self) 

        del self.item 

 

    def add_child(self, child, update=False): 

        self.children.append(child) 

        self.child_count += 1 

        if isinstance(self.item, Container): 

            self.item.childCount += 1 

        if update: 

            self.update_id += 1 

        self.sorted = False 

 

    def remove_child(self, child): 

        # print("remove_from %d (%s) child %d (%s)" % ( 

        #     self.id, self.get_name(), child.id, child.get_name())) 

        if child in self.children: 

            self.child_count -= 1 

            if isinstance(self.item, Container): 

                self.item.childCount -= 1 

            self.children.remove(child) 

            self.update_id += 1 

        self.sorted = False 

 

    def get_children(self, start=0, request_count=0): 

        if not self.sorted: 

            self.children.sort(key=_natural_key) 

            self.sorted = True 

        if request_count == 0: 

            return self.children[start:] 

        else: 

            return self.children[start:request_count] 

 

    def get_child_count(self): 

        return self.child_count 

 

    def get_id(self): 

        return self.id 

 

    def get_update_id(self): 

        if hasattr(self, 'update_id'): 

            return self.update_id 

        else: 

            return None 

 

    def get_path(self): 

        if self.mimetype in ['directory', 'root']: 

            return None 

        if isinstance(self.location, FilePath): 

            return self.location.path 

        else: 

            return self.location 

 

    def get_realpath(self): 

        if isinstance(self.location, FilePath): 

            return self.location.path 

        else: 

            return self.location 

 

    def set_path(self, path=None, extension=None): 

        if path is None: 

            path = self.get_path() 

        if extension is not None: 

            path, old_ext = os.path.splitext(path) 

            path = ''.join((path, extension)) 

        if isinstance(self.location, FilePath): 

            self.location = FilePath(path) 

        else: 

            self.location = path 

 

    def get_name(self): 

        if isinstance(self.location, FilePath): 

            name = self.location.basename() 

        else: 

            name = self.location 

        return name 

 

    def get_cover(self): 

        if self.cover: 

            return self.cover 

        try: 

            return self.parent.cover 

        except AttributeError: 

            return None 

 

    def get_parent(self): 

        return self.parent 

 

    def get_item(self): 

        return self.item 

 

    def get_xml(self): 

        return self.item.toString() 

 

    def __repr__(self): 

        return 'id: ' + str(self.id) + ' @ ' + \ 

               str(self.get_name().encode('ascii', 'xmlcharrefreplace')) 

 

 

class FSStore(BackendStore): 

    logCategory = 'fs_store' 

 

    implements = ['MediaServer'] 

 

    description = """MediaServer exporting files from the file-system""" 

 

    options = [ 

        {'option': 'name', 'type': 'string', 'default': 'my media', 

         'help': 'the name under this MediaServer ' 

                 'shall show up with on other UPnP clients'}, 

        {'option': 'version', 'type': 'int', 'default': 2, 'enum': (2, 1), 

         'help': 'the highest UPnP version this MediaServer shall support', 

         'level': 'advance'}, 

        {'option': 'uuid', 'type': 'string', 

         'help': 'the unique (UPnP) identifier for this MediaServer,' 

                 ' usually automatically set', 

         'level': 'advance'}, 

        {'option': 'content', 'type': 'string', 'default': xdg_content(), 

         'help': 'the path(s) this MediaServer shall export'}, 

        {'option': 'ignore_patterns', 'type': 'string', 

         'help': 'list of regex patterns, matching filenames will be ignored'}, 

        {'option': 'enable_inotify', 'type': 'string', 'default': 'yes', 

         'help': 'enable real-time monitoring of the content folders'}, 

        {'option': 'enable_destroy', 'type': 'string', 'default': 'no', 

         'help': 'enable deleting a file via an UPnP method'}, 

        {'option': 'import_folder', 'type': 'string', 

         'help': 'The path to store files imported via an UPnP method, ' 

                 'if empty the Import method is disabled'} 

    ] 

 

    def __init__(self, server, **kwargs): 

        BackendStore.__init__(self, server, **kwargs) 

        self.next_id = 1000 

        self.name = kwargs.get('name', 'my media') 

        self.content = kwargs.get('content', None) 

        if self.content is not None: 

            if isinstance(self.content, str): 

                self.content = [self.content] 

            cl = [] 

            for a in self.content: 

                cl += a.split(',') 

            self.content = cl 

        else: 

            self.content = xdg_content() 

            self.content = [x[0] for x in self.content] 

        if self.content is None: 

            self.content = 'tests/content' 

        if not isinstance(self.content, list): 

            self.content = [self.content] 

        self.content = set([os.path.abspath(x) for x in self.content]) 

        ignore_patterns = kwargs.get('ignore_patterns', []) 

        self.store = {} 

 

        self.inotify = None 

 

        if kwargs.get('enable_inotify', 'yes') == 'yes': 

            if INotify: 

                try: 

                    self.inotify = INotify() 

                    self.inotify.startReading() 

                except Exception as msg: 

                    self.error("inotify disabled: %s", msg) 

                    self.inotify = None 

            else: 

                self.info("%s", no_inotify_reason) 

        else: 

            self.info("FSStore content auto-update disabled upon user request") 

 

        if kwargs.get('enable_destroy', 'no') == 'yes': 

            self.upnp_DestroyObject = self.hidden_upnp_DestroyObject 

 

        self.import_folder = kwargs.get('import_folder', None) 

        if self.import_folder is not None: 

            self.import_folder = os.path.abspath(self.import_folder) 

            if not os.path.isdir(self.import_folder): 

                self.import_folder = None 

 

        self.ignore_file_pattern = re.compile( 

            r'|'.join([r'^\..*'] + list(ignore_patterns))) 

        parent = None 

        self.update_id = 0 

        if (len(self.content) > 1 or 

                utils.means_true(kwargs.get('create_root', False)) or 

                self.import_folder is not None): 

            UPnPClass = classChooser('root') 

            id = str(self.getnextID()) 

            try: 

                parent = self.store[id] = FSItem( 

                    id, parent, 'media', 'root', 

                    self.urlbase, UPnPClass, update=True, store=self) 

            except Exception as e: 

                self.error('Error on setting self.stor[id}, Error on FSItem: ' 

                           '{}'.format(e)) 

                exit(1) 

 

        if self.import_folder is not None: 

            id = str(self.getnextID()) 

            self.store[id] = FSItem( 

                id, parent, self.import_folder, 'directory', 

                self.urlbase, UPnPClass, update=True, store=self) 

            self.import_folder_id = id 

        for bytesPath in self.content: 

            if isinstance(bytesPath, (list, tuple)): 

                path = str(path[0]) 

            else: 

                path = str(bytesPath) 

            if self.ignore_file_pattern.match(path): 

                continue 

            try: 

                self.walk(path, parent, self.ignore_file_pattern) 

            except Exception as msg: 

                self.warning('on walk of %r: %r', path, msg) 

                import traceback 

                self.debug(traceback.format_exc()) 

 

        self.wmc_mapping.update({'14': '0', 

                                 '15': '0', 

                                 '16': '0', 

                                 '17': '0' 

                                 }) 

 

        louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self) 

 

    def __repr__(self): 

        return str(self.__class__).split('.')[-1] 

 

    def release(self): 

        if self.inotify is not None: 

            self.inotify.stopReading() 

 

    def len(self): 

        return len(self.store) 

 

    def get_by_id(self, id): 

        # print "get_by_id", id, type(id) 

        # we have referenced ids here when we are in WMC mapping mode 

        if isinstance(id, str): 

            id = id.split('@', 1)[0] 

        elif isinstance(id, bytes): 

            id = id.decode('utf-8').split('@', 1)[0] 

        elif isinstance(id, int): 

            id = str(id) 

        # try: 

        #    id = int(id) 

        # except ValueError: 

        #    id = 1000 

 

        if id == '0': 

            id = '1000' 

        # print "get_by_id 2", id 

        try: 

            r = self.store[id] 

        except KeyError: 

            r = None 

        # print "get_by_id 3", r 

        return r 

 

    def get_id_by_name(self, parent='0', name=''): 

        self.info('get_id_by_name %r (%r) %r', parent, type(parent), name) 

        try: 

            parent = self.store[parent] 

            self.debug("%r %d", parent, len(parent.children)) 

            for child in parent.children: 

                # if not isinstance(name, unicode): 

                #    name = name.decode("utf8") 

                self.debug("%r %r %r", child.get_name(), child.get_realpath(), 

                           name == child.get_realpath()) 

                if name == child.get_realpath(): 

                    return child.id 

        except Exception as e: 

            self.error('get_id_by_name: %r' % (e,)) 

            import traceback 

            self.info(traceback.format_exc()) 

        self.debug('get_id_by_name not found') 

 

        return None 

 

    def get_url_by_name(self, parent='0', name=''): 

        self.info('get_url_by_name %r %r', parent, name) 

        id = self.get_id_by_name(parent, name) 

        # print 'get_url_by_name', id 

        if id is None: 

            return '' 

        return self.store[id].url 

 

    def update_config(self, **kwargs): 

        self.info("update_config: {}".format(kwargs)) 

        if 'content' in kwargs: 

            new_content = kwargs['content'] 

            new_content = set( 

                [os.path.abspath(x) for x in new_content.split(',')]) 

            new_folders = new_content.difference(self.content) 

            obsolete_folders = self.content.difference(new_content) 

            self.debug('new folders: {}\nobsolete folders: {}'.format( 

                new_folders, obsolete_folders)) 

            for folder in obsolete_folders: 

                self.remove_content_folder(folder) 

            for folder in new_folders: 

                self.add_content_folder(folder) 

            self.content = new_content 

 

    def add_content_folder(self, path): 

        path = os.path.abspath(path) 

        if path not in self.content: 

            self.content.add(path) 

            self.walk(path, self.store['1000'], self.ignore_file_pattern) 

 

    def remove_content_folder(self, path): 

        path = os.path.abspath(path) 

        if path in self.content: 

            id = self.get_id_by_name('1000', path) 

            self.remove(id) 

            self.content.remove(path) 

 

    def walk(self, path, parent=None, ignore_file_pattern=''): 

        self.debug("walk %r", path) 

        containers = [] 

        parent = self.append(path, parent) 

        if parent is not None: 

            containers.append(parent) 

        while len(containers) > 0: 

            container = containers.pop() 

            try: 

                self.debug('adding %r', container.location) 

                self.info('walk.adding: {}'.format(container.location)) 

                for child in container.location.children(): 

                    if ignore_file_pattern.match(child.basename()) is not None: 

                        continue 

                    new_container = self.append(child.path, container) 

                    if new_container is not None: 

                        containers.append(new_container) 

            except UnicodeDecodeError: 

                self.warning( 

                    "UnicodeDecodeError - " 

                    "there is something wrong with a file located in %r", 

                    container.get_path()) 

 

    def create(self, mimetype, path, parent): 

        self.debug("create  %s %s %s %s", mimetype, path, type(path), parent) 

        UPnPClass = classChooser(mimetype) 

        if UPnPClass is None: 

            return None 

 

        id = self.getnextID() 

        if mimetype in ('root', 'directory'): 

            id = str(id) 

        else: 

            _, ext = os.path.splitext(path) 

            id = str(id) + ext.lower() 

        update = False 

        if hasattr(self, 'update_id'): 

            update = True 

 

        self.store[id] = FSItem(id, parent, path, mimetype, self.urlbase, 

                                UPnPClass, update=True, store=self) 

        if hasattr(self, 'update_id'): 

            self.update_id += 1 

            # print self.update_id 

            if self.server: 

                if hasattr(self.server, 'content_directory_server'): 

                    self.server.content_directory_server.set_variable( 

                        0, 'SystemUpdateID', self.update_id) 

            if parent is not None: 

                value = (parent.get_id(), parent.get_update_id()) 

                if self.server: 

                    if hasattr(self.server, 'content_directory_server'): 

                        self.server.content_directory_server.set_variable( 

                            0, 'ContainerUpdateIDs', value) 

 

        return id 

 

    def append(self, bytes_path, parent): 

        path = str(bytes_path) 

        self.debug("append  %s %s %s", path, type(path), parent) 

        if not os.path.exists(path): 

            self.warning("path %r not available - ignored", path) 

            return None 

 

        if stat.S_ISFIFO(os.stat(path).st_mode): 

            self.warning("path %r is a FIFO - ignored", path) 

            return None 

 

        try: 

            mimetype, _ = mimetypes.guess_type(path, strict=False) 

            if mimetype is None: 

                if os.path.isdir(path): 

                    mimetype = 'directory' 

            if mimetype is None: 

                return None 

 

            id = self.create(mimetype, path, parent) 

 

            if mimetype == 'directory': 

                if self.inotify is not None: 

                    mask = \ 

                        IN_CREATE | IN_DELETE | IN_MOVED_FROM | \ 

                        IN_MOVED_TO | IN_CHANGED 

                    self.inotify.watch( 

                        FilePath(os.path.abspath(path)), 

                        mask=mask, autoAdd=False, 

                        callbacks=[partial(self.notify, parameter=id)]) 

                return self.store[id] 

        except OSError as os_msg: 

            """ 

            seems we have some permissions issues along the content path 

            """ 

            self.warning("path %r isn't accessible, error %r", path, os_msg) 

 

        return None 

 

    def remove(self, id): 

        self.debug('FSSTore remove id: {}'.format(id)) 

        try: 

            item = self.store[id] 

            parent = item.get_parent() 

            item.remove() 

            del self.store[id] 

            if hasattr(self, 'update_id'): 

                self.update_id += 1 

                if self.server: 

                    self.server.content_directory_server.set_variable( 

                        0, 'SystemUpdateID', self.update_id) 

                # value = '%d,%d' % (parent.get_id(),parent_get_update_id()) 

                value = (parent.get_id(), parent.get_update_id()) 

                if self.server: 

                    self.server.content_directory_server.set_variable( 

                        0, 'ContainerUpdateIDs', value) 

 

        except KeyError: 

            pass 

 

    def notify(self, ignore, path, mask, parameter=None): 

        self.info("Event %s on %s - parameter %r", 

                  ', '.join(self.inotify.flag_to_human(mask)), path.path, 

                  parameter) 

 

        if mask & IN_CHANGED: 

            # FIXME react maybe on access right changes, loss of read rights? 

            # print('%s was changed, parent %d (%s)' % ( 

            #     path, parameter, iwp.path)) 

            pass 

 

        if mask & IN_DELETE or mask & IN_MOVED_FROM: 

            self.info('%s was deleted, parent %r (%s)', path.path, parameter, 

                      path.parent.path) 

            id = self.get_id_by_name(parameter, path.path) 

            if id is not None: 

                self.remove(id) 

        if mask & IN_CREATE or mask & IN_MOVED_TO: 

            if mask & IN_ISDIR: 

                self.info('directory %s was created, parent %r (%s)', 

                          path.path, parameter, path.parent.path) 

            else: 

                self.info('file %s was created, parent %r (%s)', path.path, 

                          parameter, path.parent.path) 

            if self.get_id_by_name(parameter, path.path) is None: 

                if path.isdir(): 

                    self.walk(path.path, self.get_by_id(parameter), 

                              self.ignore_file_pattern) 

                else: 

                    if self.ignore_file_pattern.match(parameter) is None: 

                        self.append( 

                            str(path.path), 

                            str(self.get_by_id(parameter))) 

 

    def getnextID(self): 

        ret = self.next_id 

        self.next_id += 1 

        return ret 

 

    def backend_import(self, item, data): 

        try: 

            f = open(item.get_path(), 'w+b') 

            if hasattr(data, 'read'): 

                data = data.read() 

            f.write(data) 

            f.close() 

            item.rebuild(self.urlbase) 

            return 200 

        except IOError: 

            self.warning("import of file %s failed", item.get_path()) 

        except Exception as msg: 

            import traceback 

            self.warning(traceback.format_exc()) 

        return 500 

 

    def upnp_init(self): 

        self.current_connection_id = None 

        if self.server: 

            self.server.connection_manager_server.set_variable( 

                0, 

                'SourceProtocolInfo', 

                [ 

                    # 'http-get:*:audio/mpeg:DLNA.ORG_PN=MP3;DLNA.ORG_OP=11;' 

                    # 'DLNA.ORG_FLAGS=01700000000000000000000000000000', 

                    # 'http-get:*:audio/x-ms-wma:DLNA.ORG_PN=WMABASE;' 

                    # 'DLNA.ORG_OP=11;DLNA.ORG_FLAGS' 

                    # '=01700000000000000000000000000000', 

                    # 'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;' 

                    # 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS' 

                    # '=00f00000000000000000000000000000', 

                    # 'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;' 

                    # 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS' 

                    # '=00f00000000000000000000000000000', 

                    # 'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;' 

                    # 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS' 

                    # '=00f00000000000000000000000000000', 

                    # 'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;' 

                    # 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS' 

                    # '=00f00000000000000000000000000000', 

                    # 'http-get:*:video/mpeg:DLNA.ORG_PN=MPEG_PS_PAL;' 

                    # 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS' 

                    # '=01700000000000000000000000000000', 

                    # 'http-get:*:video/x-ms-wmv:DLNA.ORG_PN=WMVMED_BASE;' 

                    # 'DLNA.ORG_OP=01;DLNA.ORG_FLAGS' 

                    # '=01700000000000000000000000000000', 

                    'internal:%s:audio/mpeg:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:audio/mpeg:*', 

                    'internal:%s:video/mp4:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:video/mp4:*', 

                    'internal:%s:application/ogg:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:application/ogg:*', 

                    'internal:%s:video/x-msvideo:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:video/x-msvideo:*', 

                    'internal:%s:video/mpeg:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:video/mpeg:*', 

                    'internal:%s:video/avi:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:video/avi:*', 

                    'internal:%s:video/divx:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:video/divx:*', 

                    'internal:%s:video/quicktime:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:video/quicktime:*', 

                    'internal:%s:image/gif:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:image/gif:*', 

                    'internal:%s:image/jpeg:*' % 

                    self.server.coherence.hostname, 

                    'http-get:*:image/jpeg:*'], 

                default=True) 

            self.server.content_directory_server.set_variable( 

                0, 'SystemUpdateID', self.update_id) 

            # self.server.content_directory_server.set_variable( 

            #     0, 'SortCapabilities', '*') 

 

    def upnp_ImportResource(self, *args, **kwargs): 

        SourceURI = kwargs['SourceURI'] 

        DestinationURI = kwargs['DestinationURI'] 

 

        if DestinationURI.endswith('?import'): 

            id = DestinationURI.split('/')[-1] 

            id = id[:-7]  # remove the ?import 

        else: 

            return failure.Failure(errorCode(718)) 

 

        item = self.get_by_id(id) 

        if item is None: 

            return failure.Failure(errorCode(718)) 

 

        def gotPage(headers): 

            # print "gotPage", headers 

            content_type = headers.get('content-type', []) 

            if not isinstance(content_type, list): 

                content_type = list(content_type) 

            if len(content_type) > 0: 

                extension = mimetypes.guess_extension(content_type[0], 

                                                      strict=False) 

                item.set_path(None, extension) 

            shutil.move(tmp_path, item.get_path()) 

            item.rebuild(self.urlbase) 

            if hasattr(self, 'update_id'): 

                self.update_id += 1 

                if self.server: 

                    if hasattr(self.server, 'content_directory_server'): 

                        self.server.content_directory_server.set_variable( 

                            0, 'SystemUpdateID', self.update_id) 

                if item.parent is not None: 

                    value = (item.parent.get_id(), item.parent.get_update_id()) 

                    if self.server: 

                        if hasattr(self.server, 'content_directory_server'): 

                            self.server.content_directory_server.set_variable( 

                                0, 'ContainerUpdateIDs', value) 

 

        def gotError(error, url): 

            self.warning("error requesting %s", url) 

            self.info(error) 

            os.unlink(tmp_path) 

            return failure.Failure(errorCode(718)) 

 

        tmp_fp, tmp_path = tempfile.mkstemp() 

        os.close(tmp_fp) 

 

        utils.downloadPage( 

            SourceURI, tmp_path).addCallbacks( 

                gotPage, gotError, None, None, [SourceURI], None) 

 

        transfer_id = 0  # FIXME 

 

        return {'TransferID': transfer_id} 

 

    def upnp_CreateObject(self, *args, **kwargs): 

        # print "CreateObject", kwargs 

        if kwargs['ContainerID'] == 'DLNA.ORG_AnyContainer': 

            if self.import_folder is not None: 

                ContainerID = self.import_folder_id 

            else: 

                return failure.Failure(errorCode(712)) 

        else: 

            ContainerID = kwargs['ContainerID'] 

        Elements = kwargs['Elements'] 

 

        parent_item = self.get_by_id(ContainerID) 

        if parent_item is None: 

            return failure.Failure(errorCode(710)) 

        if parent_item.item.restricted: 

            return failure.Failure(errorCode(713)) 

 

        if len(Elements) == 0: 

            return failure.Failure(errorCode(712)) 

 

        elt = DIDLElement.fromString(Elements) 

        if elt.numItems() != 1: 

            return failure.Failure(errorCode(712)) 

 

        item = elt.getItems()[0] 

        if item.parentID == 'DLNA.ORG_AnyContainer': 

            item.parentID = ContainerID 

        if (item.id != '' or 

                item.parentID != ContainerID or 

                item.restricted is True or 

                item.title == ''): 

            return failure.Failure(errorCode(712)) 

 

        if ('..' in item.title or 

                '~' in item.title or 

                os.sep in item.title): 

            return failure.Failure(errorCode(712)) 

 

        if item.upnp_class == 'object.container.storageFolder': 

            if len(item.res) != 0: 

                return failure.Failure(errorCode(712)) 

            path = os.path.join(parent_item.get_path(), item.title) 

            id = self.create('directory', path, parent_item) 

            try: 

                os.mkdir(path) 

            except Exception: 

                self.remove(id) 

                return failure.Failure(errorCode(712)) 

 

            if self.inotify is not None: 

                mask = \ 

                    IN_CREATE | IN_DELETE | IN_MOVED_FROM | \ 

                    IN_MOVED_TO | IN_CHANGED 

                self.inotify.watch( 

                    path, mask=mask, autoAdd=False, 

                    callbacks=[partial(self.notify, parameter=id)]) 

 

            new_item = self.get_by_id(id) 

            didl = DIDLElement() 

            didl.addItem(new_item.item) 

            return {'ObjectID': id, 'Result': didl.toString()} 

 

        if item.upnp_class.startswith('object.item'): 

            _, _, content_format, _ = item.res[0].protocolInfo.split(':') 

            extension = mimetypes.guess_extension(content_format, strict=False) 

            path = os.path.join(parent_item.get_realpath(), 

                                item.title + extension) 

            id = self.create('item', path, parent_item) 

 

            new_item = self.get_by_id(id) 

            for res in new_item.item.res: 

                res.importUri = new_item.url + '?import' 

                res.data = None 

            didl = DIDLElement() 

            didl.addItem(new_item.item) 

            return {'ObjectID': id, 'Result': didl.toString()} 

 

        return failure.Failure(errorCode(712)) 

 

    def hidden_upnp_DestroyObject(self, *args, **kwargs): 

        ObjectID = kwargs['ObjectID'] 

 

        item = self.get_by_id(ObjectID) 

        if item is None: 

            return failure.Failure(errorCode(701)) 

 

        self.info("upnp_DestroyObject: {}".format(item.location)) 

        try: 

            item.location.remove() 

        except Exception as msg: 

            self.error('upnp_DestroyObject [{}]: {}'.format(Exception, msg)) 

            return failure.Failure(errorCode(715)) 

 

        return {} 

 

 

if __name__ == '__main__': 

    from twisted.internet import reactor 

 

    p = 'tests/content' 

    f = FSStore(None, name='my media', content=p, 

                urlbase='http://localhost/xyz') 

 

    print(f.len()) 

    print(f.get_by_id(1000).child_count, f.get_by_id(1000).get_xml()) 

    print(f.get_by_id(1001).child_count, f.get_by_id(1001).get_xml()) 

    print(f.get_by_id(1002).child_count, f.get_by_id(1002).get_xml()) 

    print(f.get_by_id(1003).child_count, f.get_by_id(1003).get_xml()) 

    print(f.get_by_id(1004).child_count, f.get_by_id(1004).get_xml()) 

    print(f.get_by_id(1005).child_count, f.get_by_id(1005).get_xml()) 

    print(f.store[1000].get_children(0, 0)) 

    # print(f.upnp_Search( 

    #     ContainerID='4', 

    #     Filter='dc:title,upnp:artist', 

    #     RequestedCount='1000', 

    #     StartingIndex='0', 

    #     SearchCriteria='(upnp:class = "object.container.album.musicAlbum")', 

    #     SortCriteria='+dc:title')) 

 

    f.upnp_ImportResource(SourceURI='http://spiegel.de', DestinationURI='ttt') 

 

    reactor.run()