brainzfs.py 4.09 KB
Newer Older
Gerion Entrup's avatar
initial  
Gerion Entrup committed
1
2
#!/usr/bin/env python3

3
import argparse
4
import sys
5
import logging
6

7
8
# workaround for sqlite pseudo concurrency
# remove it once python supports fully concurrency in sqlite
9
import sqlitequeue
10
import model
11
import settings
12

13
from sqlalchemy import create_engine
14
from sqlalchemy.orm import sessionmaker, scoped_session
Gerion Entrup's avatar
Gerion Entrup committed
15
from sqlalchemy.pool import StaticPool
16
17

from collector import Collector
Gerion Entrup's avatar
Gerion Entrup committed
18
from translator import Translator
Gerion Entrup's avatar
Gerion Entrup committed
19
from schedu import Schedu
20

21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def _init_database(dbfile):
    """Initialize the database. Currently only sqlite

    Arguments:
    dbfile -- the path of the database
    """
    database = 'sqlite:///'
    engine = create_engine(database + dbfile,
                           connect_args={'check_same_thread':False},
                           #echo = True,
                           poolclass=StaticPool)
    model.init_database(engine)
    session_factory = sessionmaker(bind=engine)
    session = scoped_session(session_factory)
    if database == 'sqlite:///':
        #dirty workaroud for sqlite non concurrent mode in python
        #remove it once python supports fully concurrency in sqlite
        session = sqlitequeue.get_Session(session)
    return session

42
43
44
45
46
47
48
49
50
51
52
53
54
55

def auto_int(arg):
    return int(arg, 0)


def check(opt, f):
    def s(value):
        if settings.check_constr(opt, f(value)):
            return f(value)
        else:
            raise argparse.ArgumentTypeError("invalid value {}".format(value))
    return s


56
57
58
59
60
def main(args):
    """Main method. Parses cmdline arguments and starts the program."""
    version = "0.1-alpha"
    parser = argparse.ArgumentParser(add_help=True,
                                     description="Create a directory structure of music with" \
61
                                                 "symlinks based on musicbrainz data. Setting commandline options is only temporary. Change the config file to set option permanently.")
62
63
64
65
66
67
68
69
70
    parser.add_argument('--version', '-V', action='version',
                        version='%(prog)s {0}'.format(version))
    parser.add_argument('sourcedir', help="filepath of source file directory")
    parser.add_argument('mountpoint', help="where it should be mounted")
    parser.add_argument('--verbose', '-v', action="store_true", default=False,
                        help="change to loglevel to info")
    parser.add_argument('--database', '-d', default="music.db", help="path of the database")
    parser.add_argument('--logfile', '-l', help="log into a logfile")

71
    # options from settings
72
73
    for opt, value in settings.get_options():
        t = type(value)
74
        h = settings.get_doc(opt)
75
        if t is str:
76
            parser.add_argument('--' + opt, help=h)
77
        elif t is bool:
78
            if value:
79
80
81
                parser.add_argument('--' + opt, action="store_false", help=h)
            else:
                parser.add_argument('--' + opt, action="store_true", help=h)
82
83
        elif issubclass(t, int):
            parser.add_argument('--' + opt, type=check(opt, auto_int), help=h)
84
85


86
87
88
89
90
91
    arg = parser.parse_args(args[1:])
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)-5s %(name)-18s %(message)s',
                        datefmt='%y-%m-%d %H:%M')
    logger = logging.getLogger('main')

92
93
94
95
    print(arg.force_clean)
    print(arg.scan_interval)

    # set settings options
96
    for opt, value in settings.get_options():
97
98
99
100
        v = getattr(arg, opt)
        if v is not None:
            setattr(settings, opt, v)

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    logger.info("initializing database")
    session = _init_database(arg.database)
    logger.info("database initialized")

    collector = Collector(session)
    collector.start()

    schedu = Schedu(session, arg.sourcedir)
    schedu.start()

    #from model import Recording
    #from mbdata.models import Release, ReleaseGroup, Track, Artist, ArtistCredit, ArtistCreditName, Medium
    #from sqlalchemy.sql import select
    #se = self.session()
    #from utils import debug_breakpoint
    #debug_breakpoint()

    translator = Translator(session, arg.mountpoint)
    translator.start()

    collector.join()
    translator.join()
Gerion Entrup's avatar
Gerion Entrup committed
123

Gerion Entrup's avatar
initial  
Gerion Entrup committed
124
if __name__ == "__main__":
125
    main(sys.argv)