aboutsummaryrefslogtreecommitdiffhomepage
path: root/models
diff options
context:
space:
mode:
Diffstat (limited to 'models')
-rw-r--r--models/pods.js274
-rw-r--r--models/videos.js272
2 files changed, 546 insertions, 0 deletions
diff --git a/models/pods.js b/models/pods.js
new file mode 100644
index 000000000..c8d08b26f
--- /dev/null
+++ b/models/pods.js
@@ -0,0 +1,274 @@
1;(function () {
2 'use strict'
3
4 var async = require('async')
5 var config = require('config')
6 var fs = require('fs')
7 var request = require('request')
8
9 var constants = require('../initializers/constants')
10 var logger = require('../helpers/logger')
11 var PodsDB = require('../initializers/database').PodsDB
12 var poolRequests = require('../lib/poolRequests')
13 var utils = require('../helpers/utils')
14
15 var pods = {}
16
17 var http = config.get('webserver.https') ? 'https' : 'http'
18 var host = config.get('webserver.host')
19 var port = config.get('webserver.port')
20
21 // ----------- Private functions -----------
22
23 function getForeignPodsList (url, callback) {
24 var path = '/api/' + constants.API_VERSION + '/pods'
25
26 request.get(url + path, function (err, response, body) {
27 if (err) throw err
28 callback(JSON.parse(body))
29 })
30 }
31
32 // ----------- Public functions -----------
33
34 pods.list = function (callback) {
35 PodsDB.find(function (err, pods_list) {
36 if (err) {
37 logger.error('Cannot get the list of the pods.', { error: err })
38 return callback(err)
39 }
40
41 return callback(null, pods_list)
42 })
43 }
44
45 // { url }
46 // TODO: check if the pod is not already a friend
47 pods.add = function (data, callback) {
48 var videos = require('./videos')
49 logger.info('Adding pod: %s', data.url)
50
51 var params = {
52 url: data.url,
53 publicKey: data.publicKey,
54 score: constants.FRIEND_BASE_SCORE
55 }
56
57 PodsDB.create(params, function (err, pod) {
58 if (err) {
59 logger.error('Cannot insert the pod.', { error: err })
60 return callback(err)
61 }
62
63 videos.addRemotes(data.videos)
64
65 fs.readFile(utils.certDir + 'peertube.pub', 'utf8', function (err, cert) {
66 if (err) {
67 logger.error('Cannot read cert file.', { error: err })
68 return callback(err)
69 }
70
71 videos.listOwned(function (err, videos_list) {
72 if (err) {
73 logger.error('Cannot get the list of owned videos.', { error: err })
74 return callback(err)
75 }
76
77 return callback(null, { cert: cert, videos: videos_list })
78 })
79 })
80 })
81 }
82
83 pods.remove = function (url, callback) {
84 var videos = require('./videos')
85 logger.info('Removing %s pod.', url)
86
87 videos.removeAllRemotesOf(url, function (err) {
88 if (err) logger.error('Cannot remove all remote videos of %s.', url)
89
90 PodsDB.remove({ url: url }, function (err) {
91 if (err) return callback(err)
92
93 logger.info('%s pod removed.', url)
94 callback(null)
95 })
96 })
97 }
98
99 pods.addVideoToFriends = function (video) {
100 // To avoid duplicates
101 var id = video.name + video.magnetUri
102 poolRequests.addToPoolRequests(id, 'add', video)
103 }
104
105 pods.removeVideoToFriends = function (video) {
106 // To avoid duplicates
107 var id = video.name + video.magnetUri
108 poolRequests.addToPoolRequests(id, 'remove', video)
109 }
110
111 pods.makeFriends = function (callback) {
112 var videos = require('./videos')
113 var pods_score = {}
114
115 logger.info('Make friends!')
116 fs.readFile(utils.certDir + 'peertube.pub', 'utf8', function (err, cert) {
117 if (err) {
118 logger.error('Cannot read public cert.', { error: err })
119 return callback(err)
120 }
121
122 var urls = config.get('network.friends')
123
124 async.each(urls, computeForeignPodsList, function () {
125 logger.debug('Pods scores computed.', { pods_score: pods_score })
126 var pods_list = computeWinningPods(urls, pods_score)
127 logger.debug('Pods that we keep computed.', { pods_to_keep: pods_list })
128
129 makeRequestsToWinningPods(cert, pods_list)
130 })
131 })
132
133 // -----------------------------------------------------------------------
134
135 function computeForeignPodsList (url, callback) {
136 // Let's give 1 point to the pod we ask the friends list
137 pods_score[url] = 1
138
139 getForeignPodsList(url, function (foreign_pods_list) {
140 if (foreign_pods_list.length === 0) return callback()
141
142 async.each(foreign_pods_list, function (foreign_pod, callback_each) {
143 var foreign_url = foreign_pod.url
144
145 if (pods_score[foreign_url]) pods_score[foreign_url]++
146 else pods_score[foreign_url] = 1
147
148 callback_each()
149 }, function () {
150 callback()
151 })
152 })
153 }
154
155 function computeWinningPods (urls, pods_score) {
156 // Build the list of pods to add
157 // Only add a pod if it exists in more than a half base pods
158 var pods_list = []
159 var base_score = urls.length / 2
160 Object.keys(pods_score).forEach(function (pod) {
161 if (pods_score[pod] > base_score) pods_list.push({ url: pod })
162 })
163
164 return pods_list
165 }
166
167 function makeRequestsToWinningPods (cert, pods_list) {
168 // Stop pool requests
169 poolRequests.deactivate()
170 // Flush pool requests
171 poolRequests.forceSend()
172
173 // Get the list of our videos to send to our new friends
174 videos.listOwned(function (err, videos_list) {
175 if (err) throw err
176
177 var data = {
178 url: http + '://' + host + ':' + port,
179 publicKey: cert,
180 videos: videos_list
181 }
182
183 utils.makeMultipleRetryRequest(
184 { method: 'POST', path: '/api/' + constants.API_VERSION + '/pods/', data: data },
185
186 pods_list,
187
188 function eachRequest (err, response, body, url, pod, callback_each_request) {
189 // We add the pod if it responded correctly with its public certificate
190 if (!err && response.statusCode === 200) {
191 pods.add({ url: pod.url, publicKey: body.cert, score: constants.FRIEND_BASE_SCORE }, function (err) {
192 if (err) logger.error('Error with adding %s pod.', pod.url, { error: err })
193
194 videos.addRemotes(body.videos, function (err) {
195 if (err) logger.error('Error with adding videos of pod.', pod.url, { error: err })
196
197 logger.debug('Adding remote videos from %s.', pod.url, { videos: body.videos })
198 return callback_each_request()
199 })
200 })
201 } else {
202 logger.error('Error with adding %s pod.', pod.url, { error: err || new Error('Status not 200') })
203 return callback_each_request()
204 }
205 },
206
207 function endRequests (err) {
208 // Now we made new friends, we can re activate the pool of requests
209 poolRequests.activate()
210
211 if (err) {
212 logger.error('There was some errors when we wanted to make friends.', { error: err })
213 return callback(err)
214 }
215
216 logger.debug('makeRequestsToWinningPods finished.')
217 return callback(null)
218 }
219 )
220 })
221 }
222 }
223
224 pods.quitFriends = function (callback) {
225 // Stop pool requests
226 poolRequests.deactivate()
227 // Flush pool requests
228 poolRequests.forceSend()
229
230 PodsDB.find(function (err, pods) {
231 if (err) return callback(err)
232
233 var request = {
234 method: 'POST',
235 path: '/api/' + constants.API_VERSION + '/pods/remove',
236 sign: true,
237 encrypt: true,
238 data: {
239 url: 'me' // Fake data
240 }
241 }
242
243 // Announce we quit them
244 utils.makeMultipleRetryRequest(request, pods, function () {
245 PodsDB.remove(function (err) {
246 poolRequests.activate()
247
248 if (err) return callback(err)
249
250 logger.info('Broke friends, so sad :(')
251
252 var videos = require('./videos')
253 videos.removeAllRemotes(function (err) {
254 if (err) return callback(err)
255
256 logger.info('Removed all remote videos.')
257 callback(null)
258 })
259 })
260 })
261 })
262 }
263
264 pods.hasFriends = function (callback) {
265 PodsDB.count(function (err, count) {
266 if (err) return callback(err)
267
268 var has_friends = (count !== 0)
269 callback(null, has_friends)
270 })
271 }
272
273 module.exports = pods
274})()
diff --git a/models/videos.js b/models/videos.js
new file mode 100644
index 000000000..626c55819
--- /dev/null
+++ b/models/videos.js
@@ -0,0 +1,272 @@
1;(function () {
2 'use strict'
3
4 var async = require('async')
5 var config = require('config')
6 var dz = require('dezalgo')
7 var fs = require('fs')
8 var webtorrent = require('../lib/webTorrentNode')
9
10 var logger = require('../helpers/logger')
11 var pods = require('./pods')
12 var VideosDB = require('../initializers/database').VideosDB
13
14 var videos = {}
15
16 var http = config.get('webserver.https') === true ? 'https' : 'http'
17 var host = config.get('webserver.host')
18 var port = config.get('webserver.port')
19
20 // ----------- Private functions -----------
21 function seedVideo (path, callback) {
22 logger.info('Seeding %s...', path)
23
24 webtorrent.seed(path, function (torrent) {
25 logger.info('%s seeded (%s).', path, torrent.magnetURI)
26
27 return callback(null, torrent)
28 })
29 }
30
31 // ----------- Public attributes ----------
32 videos.uploadDir = __dirname + '/../' + config.get('storage.uploads')
33
34 // ----------- Public functions -----------
35 videos.list = function (callback) {
36 VideosDB.find(function (err, videos_list) {
37 if (err) {
38 logger.error('Cannot get list of the videos.', { error: err })
39 return callback(err)
40 }
41
42 return callback(null, videos_list)
43 })
44 }
45
46 videos.listOwned = function (callback) {
47 // If namePath is not null this is *our* video
48 VideosDB.find({ namePath: { $ne: null } }, function (err, videos_list) {
49 if (err) {
50 logger.error('Cannot get list of the videos.', { error: err })
51 return callback(err)
52 }
53
54 return callback(null, videos_list)
55 })
56 }
57
58 videos.add = function (data, callback) {
59 var video_file = data.video
60 var video_data = data.data
61
62 logger.info('Adding %s video.', video_file.path)
63 seedVideo(video_file.path, function (err, torrent) {
64 if (err) {
65 logger.error('Cannot seed this video.', { error: err })
66 return callback(err)
67 }
68
69 var params = {
70 name: video_data.name,
71 namePath: video_file.filename,
72 description: video_data.description,
73 magnetUri: torrent.magnetURI,
74 podUrl: http + '://' + host + ':' + port
75 }
76
77 VideosDB.create(params, function (err, video) {
78 if (err) {
79 logger.error('Cannot insert this video.', { error: err })
80 return callback(err)
81 }
82
83 // Now we'll add the video's meta data to our friends
84 params.namePath = null
85
86 pods.addVideoToFriends(params)
87 callback(null)
88 })
89 })
90 }
91
92 videos.remove = function (id, callback) {
93 // Maybe the torrent is not seeded, but we catch the error to don't stop the removing process
94 function removeTorrent (magnetUri, callback) {
95 try {
96 webtorrent.remove(magnetUri, callback)
97 } catch (err) {
98 logger.warn('Cannot remove the torrent from WebTorrent', { err: err })
99 return callback(null)
100 }
101 }
102
103 VideosDB.findById(id, function (err, video) {
104 if (err || !video) {
105 if (!err) err = new Error('Cannot find this video.')
106 logger.error('Cannot find this video.', { error: err })
107 return callback(err)
108 }
109
110 if (video.namePath === null) {
111 var error_string = 'Cannot remove the video of another pod.'
112 logger.error(error_string)
113 return callback(new Error(error_string))
114 }
115
116 logger.info('Removing %s video', video.name)
117
118 removeTorrent(video.magnetUri, function () {
119 VideosDB.findByIdAndRemove(id, function (err) {
120 if (err) {
121 logger.error('Cannot remove the torrent.', { error: err })
122 return callback(err)
123 }
124
125 fs.unlink(videos.uploadDir + video.namePath, function (err) {
126 if (err) {
127 logger.error('Cannot remove this video file.', { error: err })
128 return callback(err)
129 }
130
131 var params = {
132 name: video.name,
133 magnetUri: video.magnetUri
134 }
135
136 pods.removeVideoToFriends(params)
137 callback(null)
138 })
139 })
140 })
141 })
142 }
143
144 // Use the magnet Uri because the _id field is not the same on different servers
145 videos.removeRemotes = function (fromUrl, magnetUris, callback) {
146 if (callback === undefined) callback = function () {}
147
148 VideosDB.find({ magnetUri: { $in: magnetUris } }, function (err, videos) {
149 if (err || !videos) {
150 logger.error('Cannot find the torrent URI of these remote videos.')
151 return callback(err)
152 }
153
154 var to_remove = []
155 async.each(videos, function (video, callback_async) {
156 callback_async = dz(callback_async)
157
158 if (video.podUrl !== fromUrl) {
159 logger.error('The pod %s has not the rights on the video of %s.', fromUrl, video.podUrl)
160 } else {
161 to_remove.push(video._id)
162 }
163
164 callback_async()
165 }, function () {
166 VideosDB.remove({ _id: { $in: to_remove } }, function (err) {
167 if (err) {
168 logger.error('Cannot remove the remote videos.')
169 return callback(err)
170 }
171
172 logger.info('Removed remote videos from %s.', fromUrl)
173 callback(null)
174 })
175 })
176 })
177 }
178
179 videos.removeAllRemotes = function (callback) {
180 VideosDB.remove({ namePath: null }, function (err) {
181 if (err) return callback(err)
182
183 callback(null)
184 })
185 }
186
187 videos.removeAllRemotesOf = function (fromUrl, callback) {
188 VideosDB.remove({ podUrl: fromUrl }, function (err) {
189 if (err) return callback(err)
190
191 callback(null)
192 })
193 }
194
195 // { name, magnetUri, podUrl }
196 // TODO: avoid doublons
197 videos.addRemotes = function (videos, callback) {
198 if (callback === undefined) callback = function () {}
199
200 var to_add = []
201
202 async.each(videos, function (video, callback_each) {
203 callback_each = dz(callback_each)
204 logger.debug('Add remote video from pod: %s', video.podUrl)
205
206 var params = {
207 name: video.name,
208 namePath: null,
209 description: video.description,
210 magnetUri: video.magnetUri,
211 podUrl: video.podUrl
212 }
213
214 to_add.push(params)
215
216 callback_each()
217 }, function () {
218 VideosDB.create(to_add, function (err, videos) {
219 if (err) {
220 logger.error('Cannot insert this remote video.', { error: err })
221 return callback(err)
222 }
223
224 return callback(null, videos)
225 })
226 })
227 }
228
229 videos.get = function (id, callback) {
230 VideosDB.findById(id, function (err, video) {
231 if (err) {
232 logger.error('Cannot get this video.', { error: err })
233 return callback(err)
234 }
235
236 return callback(null, video)
237 })
238 }
239
240 videos.search = function (name, callback) {
241 VideosDB.find({ name: new RegExp(name) }, function (err, videos) {
242 if (err) {
243 logger.error('Cannot search the videos.', { error: err })
244 return callback(err)
245 }
246
247 return callback(null, videos)
248 })
249 }
250
251 videos.seedAll = function (callback) {
252 VideosDB.find({ namePath: { $ne: null } }, function (err, videos_list) {
253 if (err) {
254 logger.error('Cannot get list of the videos to seed.', { error: err })
255 return callback(err)
256 }
257
258 async.each(videos_list, function (video, each_callback) {
259 seedVideo(videos.uploadDir + video.namePath, function (err) {
260 if (err) {
261 logger.error('Cannot seed this video.', { error: err })
262 return callback(err)
263 }
264
265 each_callback(null)
266 })
267 }, callback)
268 })
269 }
270
271 module.exports = videos
272})()