This repository has been archived by the owner on Sep 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
elisa_viihde_fuse.py
executable file
·276 lines (248 loc) · 10.3 KB
/
elisa_viihde_fuse.py
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
#!/usr/bin/env python3
#
# Elisa Viihde File System in Userspace (FUSE)
# Copyright (c) 2016, Tomi Leppänen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from collections import namedtuple
from datetime import datetime, timedelta
from elisaviihde import elisaviihde
from fuse import FUSE, FuseOSError, Operations, LoggingMixIn
from time import strptime, strftime
import errno, logging, os, re, requests, stat
# Tell requests to shut up
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
TIME_FORMATTED = r'(?P<time>\d{2}\.\d{2}\.\d{4} \d{2}\.\d{2})'
TIME_ISO = r'(?P<time>\d{4}-\d{2}-\d{2} \d{2}\:\d{2})'
FILENAME_FORMATTED = r'(?P<name>.*) ' + TIME_FORMATTED + r'\.mpg'
FILENAME_ISO = r'(?P<name>.*) ' + TIME_ISO + '\.mpg'
TIME_FORMATTED_RE = re.compile(TIME_FORMATTED)
TIME_ISO_RE = re.compile(TIME_ISO)
FILENAME_FORMATTED_RE = re.compile(FILENAME_FORMATTED)
FILENAME_ISO_RE = re.compile(FILENAME_ISO)
TIME_FORMAT = '%d.%m.%Y %H.%M'
TIME_ISO_FORMAT = '%Y-%m-%d %H:%M'
CACHE_INVALIDATE_TIME = timedelta(0, 3600)
DirCache = namedtuple('DirCache', ['folders', 'recordings'])
StreamUriCache = namedtuple('StreamUriCache', ['uri', 'time'])
class ElisaviihdeFUSE(LoggingMixIn, Operations):
FOLDER = 0
PROGRAM = 1
def __init__(self, username, password, formatted_time=False):
self.elisaviihde = elisaviihde()
self.formatted_time = formatted_time
self._dir_cache = {}
self._stream_uri_cache = {}
try:
self.elisaviihde.login(username, password)
except Exception as error:
raise ValueError("Invalid credientials") from error
def _get_folder_id(self, path, dir_id=None):
if path in ('/', ''):
return 0
path, name = path.rsplit('/', 1)
if dir_id is None:
dir_id = self._get_folder_id(path)
try:
listing = self.elisaviihde.getfolders(dir_id)
except Exception as error:
raise FuseOSError(errno.EIO) from error
for folder in listing:
if folder['name'] == name:
return folder['id']
else:
raise FuseOSError(errno.ENOENT)
def _get_program_info(self, path, dir_id=None):
if dir_id is None:
parent_path, name = path.rsplit('/', 1)
dir_id = self._get_folder_id(parent_path)
else:
name = path.rsplit("/", 1)[1]
name = self._parse_filename(name)
if name is None:
raise FuseOSError(errno.ENOENT)
if dir_id not in self._dir_cache:
try:
listing = self.elisaviihde.getrecordings(dir_id)
except Exception as error:
raise FuseOSError(errno.EIO) from error
else:
listing = self._dir_cache[dir_id].recordings
for recording in listing:
if recording['name'] == name.group('name'):
if self.formatted_time:
if recording['startTime'] == name.group('time'):
return recording
else:
startTime = self._get_iso_time(recording['startTime'])
if startTime == name.group('time'):
return recording
else:
raise FuseOSError(errno.ENOENT)
def _get_program_id(self, path, dir_id=None):
return self._get_program_info(path, dir_id)['programId']
def _get_type(self, path):
if path.endswith('.mpg'):
return self.PROGRAM
else:
return self.FOLDER
def _stat_program(self, path, dir_id=None):
info = self._get_program_info(path, dir_id)
time = info['startTimeUTC'] / 1000
uri = self.elisaviihde.getstreamuri(info['programId'])
response = requests.head(uri, allow_redirects=True)
size = int(response.headers.get('Content-Length', 4096))
return {
'st_mode' : 0o444 | stat.S_IFREG,
'st_nlink' : 1,
'st_uid' : os.getuid(),
'st_gid' : os.getgid(),
'st_size' : size,
'st_blksize' : 128*1024,
'st_atime' : time,
'st_mtime' : time,
'st_ctime' : time,
}
def _stat_folder(self, path, dir_id=None):
if dir_id is None:
dir_id = self._get_folder_id(path)
return {
'st_mode' : 0o555 | stat.S_IFDIR,
'st_nlink' : 1,
'st_uid' : os.getuid(),
'st_gid' : os.getgid(),
'st_size' : 0,
'st_atime' : 0,
'st_mtime' : 0,
'st_ctime' : 0,
}
def _create_filename(self, program):
if self.formatted_time:
startTime = program['startTime']
else:
startTime = self._get_iso_time(program['startTime'])
return '{} {}.mpg'.format(program['name'], startTime)
def _parse_filename(self, name):
if self.formatted_time:
return FILENAME_FORMATTED_RE.match(name)
return FILENAME_ISO_RE.match(name)
def _get_iso_time(self, time):
return strftime(TIME_ISO_FORMAT, strptime(time, TIME_FORMAT))
def getattr(self, path, fh=None):
type_ = self._get_type(path)
if type_ == self.FOLDER:
return self._stat_folder(path)
else:
return self._stat_program(path)
def open(self, path, flags):
return self._get_program_id(path)
def opendir(self, path):
dir_id = self._get_folder_id(path)
try:
folders = self.elisaviihde.getfolders(dir_id)
recordings = self.elisaviihde.getrecordings(dir_id)
except Exception as error:
raise FuseOSError(errno.EIO) from error
self._dir_cache[dir_id] = DirCache(folders, recordings)
return self._get_folder_id(path)
def read(self, path, size, offset, fh):
if (fh in self._stream_uri_cache and
datetime.now() - self._stream_uri_cache[fh].time <
CACHE_INVALIDATE_TIME):
uri = self._stream_uri_cache[fh].uri
self._stream_uri_cache[fh] = StreamUriCache(uri, datetime.now())
else:
try:
uri = self.elisaviihde.getstreamuri(fh)
except Exception as error:
raise FuseOSError(errno.EACCES) from error
response = requests.get(uri, stream=True, headers={
'Range': 'bytes={}-{}'.format(offset, offset+size)
})
try:
response.raise_for_status()
except requests.exceptions.HTTPError:
raise FuseOSError(errno.EIO)
return response.raw.read(size)
def readdir(self, path, fh): # FIXME: Add attrs and stuff!
if fh not in self._dir_cache:
raise FuseOSError(errno.EIO) # FIXME: Check errno
listing = ['.', '..']
for folder in self._dir_cache[fh].folders:
listing.append(folder['name'])
for recording in self._dir_cache[fh].recordings:
listing.append(self._create_filename(recording))
return listing
def releasedir(self, path, fh):
if fh not in self._dir_cache:
return 0
del self._dir_cache[fh]
return 0
def destroy(self, path):
self.elisaviihde.close()
self.elisaviihde = None
return 0
def __call__(self, op, path, *args):
if op in ('read', 'readdir'):
self.log.debug('-> %s %s %s', op, path, repr(args))
try:
data = getattr(self, op)(path, *args)
self.log.debug('<- %s len %s', op, len(data))
return data
except OSError as e:
self.log.debug('<- %s %s', op, repr(str(e)))
raise
except Exception:
self.log.debug('<- %s [Unhandled Exception]', op)
raise
else:
return super().__call__(op, path, *args)
if __name__ == "__main__":
import sys, argparse
parser = argparse.ArgumentParser(
description="Elisa Viihde File System in Userspace (FUSE)")
parser.add_argument('mountpoint', help="mountpoint")
parser.add_argument('username', help="your Elisa Viihde username")
parser.add_argument('password', help="your Elisa Viihde password")
parser.add_argument('-t', '--format-time', action='store_true',
default=False, help="use Finnish time formatting in filenames")
parser.add_argument('-n', '--no-fork', action='store_true', default=False,
help="don't fork, leave running on foreground")
parser.add_argument('-f', '--fork', action='store_false', dest='no_fork',
help="fork even if --no-fork is set")
parser.add_argument('-d', '--debug', action='store_true', default=False,
help="set debugging on, requires --no-fork")
args = parser.parse_args()
if args.debug:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger.debug("Set logging to DEBUG level")
try:
ev = ElisaviihdeFUSE(args.username, args.password, args.format_time)
except ValueError as error:
print(error, file=sys.stderr)
sys.exit(32) # see mount(8)
if args.no_fork:
print("Not forking, press Ctrl+c to quit!")
fuse = FUSE(ev, args.mountpoint, foreground=True)
else:
fuse = FUSE(ev, args.mountpoint)
sys.exit(0)