Setting up a trunk for branching
[nqaap] / src / opt / Nqa-Audiobook-player / FileStorage.py
1 from __future__ import with_statement   # enable with
2
3 import os
4
5 import logging
6
7
8 log = logging.getLogger(__name__)
9
10
11 class FileStorage(object):
12
13     def __init__(self, path="~/.SornPlayer/"):
14         # Setup dir
15         log.info("init filestorage")
16         self.path = path
17         self.books_path = os.path.join(self.path, "books/")
18         if not os.path.isdir(self.books_path):
19             os.makedirs(self.books_path)
20
21         # Read config file
22         self.conf = os.path.join(self.path, "current")
23         self.selected = None
24
25         if os.path.isfile(self.conf):
26             with open(self.conf) as f:
27                 self.selected = f.readline()
28
29         # Read current book file
30
31     def get_selected(self):
32         """returns the currently selected book"""
33         return self.selected
34
35     def select_book(self, bookName):
36         """ Sets the book as the currently playing, and adds it to the
37         database if it is not already there"""
38         book_file = os.path.join(self.books_path, bookName)
39         if not os.path.isfile(book_file):
40             with open(book_file, 'w') as f:
41                 f.write("0\n") #Current chapter
42                 f.write("0\n") #Current position
43
44         self.selected = bookName
45         with open(self.conf, 'w') as f:
46             f.write(self.selected) #
47
48     def set_time(self, chapter, position):
49         """ Sets the current time for the book that is currently selected"""
50         try:
51             book_file = os.path.join(self.books_path, self.selected)
52             log.debug("writing time (%s, %s) to: %s"%( chapter, position, book_file ))
53             with open(book_file, 'w') as f:
54                 f.write(str(int(chapter)) + "\n") #Current chapter
55                 f.write(str(int(position)) + "\n") #Current position
56         except:
57             log.error("Unable to save to file: %s" % book_file)
58
59     def get_time(self):
60         """Returns the current saved time for the current selected book"""
61         chapter, position = 0 , 0
62         book_file = os.path.join(self.books_path, self.selected)
63         log.debug("getting time from: " + book_file)
64         with open(book_file, 'r') as f:
65             chapter = int(f.readline())
66             position = int(f.readline())
67
68         return chapter, position