summaryrefslogtreecommitdiff
path: root/p2pvr/lib/storage.cpp
blob: 9d9345d4cd84d0710e52fd5675be60a3f075b659 (plain)
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
#include <pch.hpp>
#include "storage.h"
#include "fileSink.h"
#include <commonHelpers.h>
#include <fcntl.h>
#include <logger.h>
#include <boost/filesystem/operations.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>

namespace fs = boost::filesystem;

fs::path Storage::root;
fs::path Storage::byAll;
fs::path Storage::byTitle;
fs::path Storage::byDate;
fs::path Storage::byService;
fs::path Storage::bySchedule;

DECLARE_OPTIONS(Storage, "P2PVR Storage options")
("p2pvr.storage.root", Options::value(&root, "recordings"),
 "Root folder in which to store recordings")
("p2pvr.storage.all", Options::value(&byAll, "all"),
 "Sub folder in which to store all recordings")
("p2pvr.storage.bytitle", Options::value(&byTitle, "title"),
 "Sub folder in which to store by title")
("p2pvr.storage.bydate", Options::value(&byDate, "date"),
 "Sub folder in which to store by date")
("p2pvr.storage.byservice", Options::value(&byService, "service"),
 "Sub folder in which to store by service")
("p2pvr.storage.byschedule", Options::value(&bySchedule, "schedule"),
 "Sub folder in which to store by schedule")
END_OPTIONS(Storage);

inline static
fs::path createPath(const fs::path & start)
{
	return start;
}

template <typename Arg>
inline static
fs::path
operator/(const fs::path & lhs, const IceUtil::Optional<Arg> & rhs)
{
	if (rhs) {
		return lhs / *rhs;
	}
	return lhs;
}

template <typename Arg, typename ... Args>
inline static
fs::path createPath(const fs::path & start, const Arg & arg, const Args & ... args)
{
	auto path = start / arg;
	return createPath(path, args...);
}

template <typename Arg, typename ... Args>
inline static
std::string firstNotNull(const Arg & arg, const Args & ...)
{
	return boost::lexical_cast<std::string>(arg);
}

template <typename Arg, typename ... Args>
inline static
std::string firstNotNull(const IceUtil::Optional<Arg> & arg, const Args & ... args)
{
	return arg ? firstNotNull(*arg, args...) : firstNotNull(args...);
}

template <typename ... Args>
inline static
std::string firstNotNull(const std::string & arg, const Args & ...)
{
	return arg;
}

inline static
std::string
formatIf(const boost::format & f)
{
	return f.str();
}

template <typename Arg, typename ... Args>
inline static
IceUtil::Optional<std::string>
formatIf(boost::format & f, const IceUtil::Optional<Arg> & arg, const Args & ... args)
{
	if (arg) {
		f % *arg;
		return formatIf(f, args...);
	}
	else {
		return IceUtil::Optional<std::string>();
	}
}

template <typename Arg, typename ... Args>
inline static
IceUtil::Optional<std::string>
formatIf(boost::format & f, const Arg & arg, const Args & ... args)
{
	f % arg;
	return formatIf(f, args...);
}

template <typename... Args>
inline static
IceUtil::Optional<std::string>
formatIf(const std::string & msgfmt, const Args & ... args)
{
	boost::format fmt(msgfmt);
	return formatIf(fmt, args...);
}

std::string
Storage::CreateForEventRecording(const std::string & ext, const P2PVR::SchedulePtr & schedule, const DVBSI::ServicePtr & service, const DVBSI::EventPtr & event, const Ice::Current &)
{
	fs::create_directories(root / byAll);
	auto id = boost::lexical_cast<std::string>(boost::uuids::random_generator()());
	fs::path path = root / byAll / id;
	path.replace_extension(ext);
	auto fd = open(path.string().c_str(), O_WRONLY | O_CREAT | O_EXCL, 0664);
	if (fd < 0) {
		Logger()->messagebf(LOG_ERR, "%s: Failed to open file for writing at %s (%d:%s)", __PRETTY_FUNCTION__,
				path, errno, strerror(errno));
		throw P2PVR::StorageException(path.string(), strerror(errno));
	}
	createSymlinks(ext, id, schedule, service, event);
	Logger()->messagebf(LOG_INFO, "%s: Created new recording %s", __PRETTY_FUNCTION__, path);

	close(fd);
	return id;
}

void
Storage::createSymlinks(const std::string & ext, const std::string & target, const P2PVR::SchedulePtr & schedule, const DVBSI::ServicePtr & service, const DVBSI::EventPtr & event)
{
	// By title, with optional season and episode information
	createSymlink(ext, target, createPath(root, byTitle,
				event->Title,
				formatIf("Season %02d", event->Season),
				firstNotNull(
					formatIf("Part %02d of %02d - %s", event->Episode, event->Episodes, event->Subtitle),
					formatIf("Episode %02d - %s", event->Episode, event->Subtitle),
					formatIf("Part %02d of %02d - %s", event->Episode, event->Episodes, event->Description),
					formatIf("Part %02d of %02d", event->Episode, event->Episodes),
					formatIf("Episode %02d - %s", event->Episode, event->Description),
					event->Subtitle,
					event->Description,
					formatIf("Episode %02d", event->Episode),
					event->StartTime)));
	// By date
	createSymlink(ext, target, createPath(root, byDate,
				formatIf("%04d-%02d-%02d", event->StartTime.Year, event->StartTime.Month, event->StartTime.Day),
				firstNotNull(
					formatIf("%s - %s", event->Title, event->Subtitle),
					formatIf("%s - %s", event->Title, event->Description),
					event->Title)));
	// By service
	createSymlink(ext, target, createPath(root, byService,
				service->Name,
				firstNotNull(
					formatIf("%s - %s", event->Title, event->Subtitle),
					formatIf("%s - %s", event->Title, event->Description),
					event->Title)));
	// By schedule title
	createSymlink(ext, target, createPath(root, bySchedule,
				formatIf("Title: %s", schedule->Title),
				formatIf("%04d-%02d-%02d", event->StartTime.Year, event->StartTime.Month, event->StartTime.Day),
				firstNotNull(
					formatIf("%s - %s", event->Title, event->Subtitle),
					formatIf("%s - %s", event->Title, event->Description),
					event->Title)));
	// By schedule search
	createSymlink(ext, target, createPath(root, bySchedule,
				formatIf("Search: %s", schedule->Search),
				firstNotNull(
					formatIf("%s - %s", event->Title, event->Subtitle),
					formatIf("%s - %s", event->Title, event->Description),
					event->Title)));
}
void
Storage::createSymlink(const std::string & ext, const std::string & target, const fs::path & link)
{
	fs::path path = link;
	path.replace_extension(ext);
	Logger()->messagebf(LOG_DEBUG, "%s: link(%s) -> target(%s)", __PRETTY_FUNCTION__, path, target);
	if (fs::exists(path)) {
		Logger()->messagebf(LOG_WARNING, "%s: symlink already exists %s", __PRETTY_FUNCTION__, path);
		return;
	}
	fs::create_directories(path.parent_path());
	fs::path relativeTarget;
	for (fs::path tmp = path.parent_path(); tmp != root; tmp = tmp.parent_path()) {
		relativeTarget /= "..";
	}
	relativeTarget /= byAll;
	relativeTarget /= target;
	relativeTarget.replace_extension(ext);
	fs::create_symlink(relativeTarget, path);
}

std::string
Storage::FindExtension(const std::string & id)
{
	fs::directory_iterator end;
	for (fs::directory_iterator itr(root / byAll); itr != end; ++itr) {
		if (itr->path().stem() == id) {
			return itr->path().extension().string();
		}
	}
	return "";
}

P2PVR::RawDataClientPrx
Storage::OpenForWrite(const std::string & id, const Ice::Current & ice)
{
	fs::path path = root / byAll / id;
	path.replace_extension(FindExtension(id));
	auto fd = open(path.string().c_str(), O_WRONLY | O_APPEND | O_LARGEFILE);
	if (fd < 0) {
		Logger()->messagebf(LOG_ERR, "%s: Failed to open file for reading at %s (%d:%s)", __PRETTY_FUNCTION__,
				path, errno, strerror(errno));
		throw P2PVR::StorageException(path.string(), strerror(errno));
	}
	auto openFile = OpenFilePtr(new OpenFile(ice.adapter, new FileSink(fd)));
	openFiles.insert(openFile);
	return *openFile;
}

void
Storage::Close(const P2PVR::RawDataClientPrx & file, const Ice::Current &)
{
	openFiles.erase(std::find_if(openFiles.begin(), openFiles.end(), [&file](const OpenFilePtr & of) { return *of == file; }));
}

void
Storage::Delete(const std::string & id, const Ice::Current &)
{
	fs::path path = root / byAll / id;
	path.replace_extension(FindExtension(id));
	Logger()->messagebf(LOG_INFO, "%s: Deleting links to %s", __PRETTY_FUNCTION__, path);
	DeleteFrom(path, fs::canonical(root));
}

void
Storage::DeleteFrom(const fs::path & path, const fs::path & from)
{
	Logger()->messagebf(LOG_DEBUG, "%s: Deleting links to %s to %s", __PRETTY_FUNCTION__, path, from);
	fs::directory_iterator end;
	for (fs::directory_iterator itr(from); itr != end; ++itr) {
		if (fs::is_directory(*itr)) {
			DeleteFrom(path, *itr);
		}
		else {
			boost::system::error_code err;
			auto link = fs::canonical(*itr, err);
			if (err || link == path) {
				Logger()->messagebf(LOG_DEBUG, "%s: deleting %s", __PRETTY_FUNCTION__, *itr);
				fs::remove(*itr);
			}
		}
	}
	if (from != root && fs::is_empty(from)) {
		Logger()->messagebf(LOG_DEBUG, "%s: deleting directory %s", __PRETTY_FUNCTION__, from);
		fs::remove(from);
	}
}