forked from joaomatossilva/OSDB.net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnonymousClient.cs
406 lines (342 loc) · 11.9 KB
/
AnonymousClient.cs
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Net;
using OSDBnet.Backend;
using CookComputing.XmlRpc;
namespace OSDBnet {
public class AnonymousClient : IAnonymousClient, IDisposable {
private bool disposed = false;
protected readonly IOsdb proxy;
protected string token;
internal AnonymousClient(IOsdb proxy) {
this.proxy = proxy;
}
internal void Login(string username, string password, string language, string userAgent) {
LoginResponse response = proxy.Login(username, password, language, userAgent);
VerifyResponseCode(response);
token = response.token;
}
public IList<Subtitle> SearchSubtitlesFromFile(string languages, string filename) {
if (string.IsNullOrEmpty(filename)) {
throw new ArgumentNullException("filename");
}
FileInfo file = new FileInfo(filename);
if (!file.Exists) {
throw new ArgumentException("File doesn't exist", "filename");
}
var request = new SearchSubtitlesRequest { sublanguageid = languages };
request.moviehash = HashHelper.ToHexadecimal(HashHelper.ComputeMovieHash(filename));
request.moviebytesize = file.Length.ToString();
request.imdbid = string.Empty;
request.query = string.Empty;
return SearchSubtitlesInternal(request);
}
public IList<Subtitle> SearchSubtitlesFromImdb(string languages, string imdbId) {
if (string.IsNullOrEmpty(imdbId)) {
throw new ArgumentNullException("imdbId");
}
var request = new SearchSubtitlesRequest {
sublanguageid = languages,
imdbid = imdbId
};
return SearchSubtitlesInternal(request);
}
public IList<Subtitle> SearchSubtitlesFromQuery(string languages, string query, int? season = null, int? episode = null) {
if (string.IsNullOrEmpty(query)) {
throw new ArgumentNullException("query");
}
var request = new SearchSubtitlesRequest {
sublanguageid = languages,
query = query,
season = season,
episode = episode
};
return SearchSubtitlesInternal(request);
}
private IList<Subtitle> SearchSubtitlesInternal(SearchSubtitlesRequest request) {
var response = proxy.SearchSubtitles(token, new SearchSubtitlesRequest[] { request });
VerifyResponseCode(response);
var subtitles = new List<Subtitle>();
var subtitlesInfo = response.data as object[];
if (null != subtitlesInfo) {
foreach (var infoObject in subtitlesInfo) {
var subInfo = SimpleObjectMapper.MapToObject<SearchSubtitlesInfo>((XmlRpcStruct)infoObject);
subtitles.Add(BuildSubtitleObject(subInfo));
}
}
return subtitles;
}
public string DownloadSubtitleToPath(string path, Subtitle subtitle)
{
return DownloadSubtitleToPath(path, subtitle, null);
}
public string DownloadSubtitleToPath(string path, Subtitle subtitle, string newSubtitleName) {
if (string.IsNullOrEmpty(path)) {
throw new ArgumentNullException("path");
}
if (null == subtitle) {
throw new ArgumentNullException("subtitle");
}
if (!Directory.Exists(path)) {
throw new ArgumentException("path should point to a valid location");
}
string destinationfile = Path.Combine(path, (string.IsNullOrEmpty(newSubtitleName)) ? subtitle.SubtitleFileName : newSubtitleName);
string tempZipName = Path.GetTempFileName();
try {
WebClient webClient = new WebClient();
webClient.DownloadFile(subtitle.SubTitleDownloadLink, tempZipName);
UnZipSubtitleFileToFile(tempZipName, destinationfile);
} finally {
File.Delete(tempZipName);
}
return destinationfile;
}
public long CheckSubHash(string subHash) {
var response = proxy.CheckSubHash(token, new string[] { subHash });
VerifyResponseCode(response);
long idSubtitleFile = 0;
var hashInfo = response.data as XmlRpcStruct;
if (null != hashInfo && hashInfo.ContainsKey(subHash)) {
idSubtitleFile = Convert.ToInt64(hashInfo[subHash]);
}
return idSubtitleFile;
}
public IEnumerable<MovieInfo> CheckMovieHash(string moviehash) {
var response = proxy.CheckMovieHash(token, new string[] { moviehash });
VerifyResponseCode(response);
var movieInfoList = new List<MovieInfo>();
var hashInfo = response.data as XmlRpcStruct;
if (null != hashInfo && hashInfo.ContainsKey(moviehash)) {
var movieInfoArray = hashInfo[moviehash] as object[];
foreach (XmlRpcStruct movieInfoStruct in movieInfoArray) {
var movieInfo = SimpleObjectMapper.MapToObject<CheckMovieHashInfo>(movieInfoStruct);
movieInfoList.Add(BuildMovieInfoObject(movieInfo));
}
}
return movieInfoList;
}
public IEnumerable<Language> GetSubLanguages() {
//get system language
return GetSubLanguages("en");
}
public IEnumerable<Language> GetSubLanguages(string language) {
var response = proxy.GetSubLanguages(language);
VerifyResponseCode(response);
IList<Language> languages = new List<Language>();
foreach (var languageInfo in response.data) {
languages.Add(BuildLanguageObject(languageInfo));
}
return languages;
}
public IEnumerable<Movie> SearchMoviesOnImdb(string query) {
var response = proxy.SearchMoviesOnIMDB(token, query);
VerifyResponseCode(response);
IList<Movie> movies = new List<Movie>();
if (response.data.Length == 1 && string.IsNullOrEmpty(response.data.First().id)) {
// no match found
return movies;
}
foreach (var movieInfo in response.data) {
movies.Add(BuildMovieObject(movieInfo));
}
return movies;
}
public MovieDetails GetImdbMovieDetails(string imdbId) {
var response = proxy.GetIMDBMovieDetails(token, imdbId);
VerifyResponseCode(response);
var movieDetails = BuildMovieDetailsObject(response.data);
return movieDetails;
}
public void NoOperation() {
var response = proxy.NoOperation(token);
VerifyResponseCode(response);
}
public IEnumerable<UserComment> GetComments(string idsubtitle) {
var response = proxy.GetComments(token, new string[] { idsubtitle });
VerifyResponseCode(response);
var comments = new List<UserComment>();
var commentsStruct = response.data as XmlRpcStruct;
if (commentsStruct == null)
return comments;
if (commentsStruct.ContainsKey("_" + idsubtitle)) {
object[] commentsList = commentsStruct["_" + idsubtitle] as object[];
if (commentsList != null) {
foreach (XmlRpcStruct commentStruct in commentsList) {
var comment = SimpleObjectMapper.MapToObject<CommentsData>(commentStruct);
comments.Add(BuildUserCommentObject(comment));
}
}
}
return comments;
}
public string DetectLanguge(string data) {
var bytes = GzipString(data);
var text = Convert.ToBase64String(bytes);
var response = proxy.DetectLanguage(token, new string[] { text } );
VerifyResponseCode(response);
var languagesStruct = response.data as XmlRpcStruct;
if (languagesStruct == null)
return null;
foreach(string key in languagesStruct.Keys){
return languagesStruct[key].ToString();
}
return null;
}
public void ReportWrongMovieHash(string idSubMovieFile) {
var response = proxy.ReportWrongMovieHash(token, idSubMovieFile);
VerifyResponseCode(response);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (!disposed) {
if (disposing && !string.IsNullOrEmpty(token)) {
try {
proxy.Logout(token);
} catch {
//soak it. We don't want exception on disposing. It's better to let the session timeout.
}
token = null;
}
disposed = true;
}
}
~AnonymousClient() {
Dispose(false);
}
protected static string Base64Encode(string str) {
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(encbuff);
}
protected static string Base64Decode(string str) {
byte[] decbuff = Convert.FromBase64String(str);
return System.Text.Encoding.UTF8.GetString(decbuff);
}
protected static byte[] GzipString(string str) {
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
msi.CopyTo(gs);
}
return mso.ToArray();
}
}
protected static string GUnzipString(byte[] gzippedString) {
using (var msi = new MemoryStream(gzippedString))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
gs.CopyTo(mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
}
protected static void UnZipSubtitleFileToFile(string zipFileName, string subFileName) {
using (FileStream subFile = File.OpenWrite(subFileName))
using (FileStream tempFile = File.OpenRead(zipFileName)) {
var gzip = new GZipStream(tempFile, CompressionMode.Decompress);
gzip.CopyTo(subFile);
}
}
protected static Subtitle BuildSubtitleObject(SearchSubtitlesInfo info) {
var sub = new Subtitle {
SubtitleId = info.IDSubtitle,
SubtitleHash = info.SubHash,
SubtitleFileName = info.SubFileName,
SubTitleDownloadLink = new Uri(info.SubDownloadLink),
SubtitlePageLink = new Uri(info.SubtitlesLink),
LanguageId = info.SubLanguageID,
LanguageName = info.LanguageName,
Rating = info.SubRating,
Bad = info.SubBad,
ImdbId = info.IDMovieImdb,
MovieId = info.IDMovie,
MovieName = info.MovieName,
OriginalMovieName = info.MovieNameEng,
MovieYear = int.Parse(info.MovieYear)
};
return sub;
}
protected static MovieInfo BuildMovieInfoObject(CheckMovieHashInfo info) {
var movieInfo = new MovieInfo {
MovieHash = info.MovieHash,
MovieImdbID = info.MovieImdbID,
MovieYear = info.MovieYear,
MovieName = info.MovieName,
SeenCount = info.SeenCount
};
return movieInfo;
}
protected static Language BuildLanguageObject(GetSubLanguagesInfo info) {
var language = new Language {
LanguageName = info.LanguageName,
SubLanguageID = info.SubLanguageID,
ISO639 = info.ISO639
};
return language;
}
protected static Movie BuildMovieObject(MoviesOnIMDBInfo info) {
var movie = new Movie {
Id = Convert.ToInt64(info.id),
Title = info.title
};
return movie;
}
protected static MovieDetails BuildMovieDetailsObject(IMDBMovieDetails info) {
var movie = new MovieDetails {
Aka = info.aka,
Cast = SimpleObjectMapper.MapToDictionary(info.cast as XmlRpcStruct),
Cover = info.cover,
Id = info.id,
Rating = info.rating,
Title = info.title,
Votes = info.votes,
Year = info.year,
Country = info.country,
Directors = SimpleObjectMapper.MapToDictionary(info.directors as XmlRpcStruct),
Duration = info.duration,
Genres = info.genres,
Language = info.language,
Tagline = info.tagline,
Trivia = info.trivia,
Writers = SimpleObjectMapper.MapToDictionary(info.writers as XmlRpcStruct)
};
return movie;
}
protected static UserComment BuildUserCommentObject(CommentsData info){
var comment = new UserComment {
Comment = info.Comment,
Created = info.Created,
IDSubtitle = info.IDSubtitle,
UserID = info.UserID,
UserNickName = info.UserNickName
};
return comment;
}
protected static void VerifyResponseCode(ResponseBase response) {
if (null == response) {
throw new ArgumentNullException("response");
}
if (string.IsNullOrEmpty(response.status)) {
//aperantly there are some methods that dont define 'status'
return;
}
int responseCode = int.Parse(response.status.Substring(0,3));
if (responseCode >= 400) {
//TODO: Create Exception type
throw new Exception(string.Format("Unexpected error response {1}", responseCode, response.status));
}
}
}
}