Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

"""LICENSE 

Copyright 2018 Hermann Krumrey <hermann@krumreyh.com> 

 

This file is part of anime-list-apis. 

 

anime-list-apis is free software: you can redistribute it and/or modify 

it under the terms of the GNU General Public License as published by 

the Free Software Foundation, either version 3 of the License, or 

(at your option) any later version. 

 

anime-list-apis is distributed in the hope that it will be useful, 

but WITHOUT ANY WARRANTY; without even the implied warranty of 

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

GNU General Public License for more details. 

 

You should have received a copy of the GNU General Public License 

along with anime-list-apis. If not, see <http://www.gnu.org/licenses/>. 

LICENSE""" 

 

import time 

import json 

import requests 

import logging 

from typing import List, Dict, Tuple, Optional, Any 

from anime_list_apis.cache.Cache import Cache 

from anime_list_apis.api.ApiInterface import ApiInterface 

from anime_list_apis.models.MediaData import MediaData 

from anime_list_apis.models.MediaListEntry import MediaListEntry 

from anime_list_apis.models.MediaUserData import MediaUserData 

from anime_list_apis.models.attributes.Date import Date 

from anime_list_apis.models.attributes.Id import Id, IdType 

from anime_list_apis.models.attributes.MediaType import MediaType 

from anime_list_apis.models.attributes.MediaFormat import MediaFormat 

from anime_list_apis.models.attributes.Relation import Relation, RelationType 

from anime_list_apis.models.attributes.Score import Score, ScoreType 

from anime_list_apis.models.attributes.Title import Title, TitleType 

 

 

class AnilistApi(ApiInterface): 

""" 

Implements a wrapper around the anilist.co API 

""" 

 

def __init__(self, cache: Cache = None, rate_limit_pause: float = 0.5): 

""" 

Initializes the Anilist Api interface. 

Intializes cache or uses the one provided. 

:param cache: The cache to use. If left as None, will use default cache 

:param rate_limit_pause: A duration in seconds that the API Interface 

will pause after a network operation to 

prevent being rate limited 

""" 

super().__init__(IdType.ANILIST, cache, rate_limit_pause) 

 

# Implemented Abstract Methods -------------------------------------------- 

 

def _get_data( 

self, 

media_type: MediaType, 

_id: Id 

) -> Optional[MediaData]: 

""" 

Retrieves a single data object using the API 

:param media_type: The media type to retrieve 

:param _id: The ID to retrieve. May be either an int or an Id object 

:return: The Anime Data or None if no valid data was found 

""" 

id_tuple = self.__resolve_query_id(media_type, _id, True) 

if id_tuple is None: 

return None 

query_id, id_type = id_tuple 

query_id_type = "id" if id_type == IdType.ANILIST else "idMal" 

 

query = """ 

query ($id: Int, $type: MediaType) { 

Media(""" + query_id_type + """: $id, type: $type) { 

""" + self.__media_query + """ 

} 

} 

""" 

 

variables = {"id": query_id, "type": media_type.name} 

data = self.__graphql_query(query, variables) 

 

if data is None: 

return None 

else: 

data = self.__generate_media_data(media_type, data["Media"]) 

self.__cache_mal_to_anilist_map( 

media_type, 

data.id.get(IdType.MYANIMELIST), 

data.id.get(IdType.ANILIST) 

) 

return data 

 

def _get_user_data( 

self, 

media_type: MediaType, 

_id: Id, 

username: str 

) -> Optional[MediaUserData]: 

""" 

Actual implementation of the get_user_data for each subclass 

:param media_type: The media type to fetch 

:param _id: The ID to retrieve 

:param username: The user for which to fetch the data 

:return: The user data for the entry or 

None if the user doesn't have such an entry 

""" 

entry = self._get_list_entry(media_type, _id, username) 

if entry is not None: 

return entry.get_user_data() 

else: 

return None 

 

def _get_user_data_list(self, media_type: MediaType, username: str) \ 

-> List[MediaUserData]: 

""" 

Retrieves a user's entire list of user data 

Actual implementation method to be implemented by subclasses 

:param media_type: The media type to fetch 

:param username: The username for which to fetch the list 

:return: The list of user data 

""" 

return list(map( 

lambda x: x.get_user_data(), 

self._get_list(media_type, username) 

)) 

 

def _get_list_entry( 

self, 

media_type: MediaType, 

_id: int or Id, 

username: str 

) -> Optional[MediaListEntry]: 

""" 

Retrieves a user list entry 

:param media_type: The media type to fetch 

:param _id: The ID to retrieve. May be and int or an Id object 

:param username: The user for which to fetch the entry 

:return: The entry for the user or 

None if the user doesn't have such an entry 

""" 

id_tuple = self.__resolve_query_id(media_type, _id, False) 

if id_tuple is None: 

return None 

query_id = id_tuple[0] 

 

# Currently we can't get all the information in one go due to some 

# 500 internal server errors. 

# Once this is fixed, the following should stand here: 

# inject = self.media_list_entry_query 

inject = self.__media_list_entry_query.replace( 

self.__media_query, 

""" 

id 

idMal 

""" 

) 

 

query = """ 

query ($id: Int, $username: String, $type: MediaType) { 

MediaList(mediaId: $id, userName: $username, type: $type) { 

""" + inject + """ 

} 

} 

""" 

variables = { 

"id": query_id, 

"type": media_type.name, 

"username": username 

} 

result = self.__graphql_query(query, variables) 

 

if result is None: 

return None 

else: 

 

# Again, due to 500 Server errors we have to hack around a bit 

# media_data = self.__generate_media_data( 

# media_type, result["MediaList"]["media"] 

# ) 

media_data = self._get_data(media_type, _id) 

 

user_data = self.__generate_media_user_data( 

media_type, result["MediaList"] 

) 

entry_cls = MediaListEntry.get_class_for_media_type(media_type) 

return entry_cls(media_data, user_data) 

 

def _get_list(self, media_type: MediaType, username: str) \ 

-> List[MediaListEntry]: 

""" 

Retrieves a user's entire list 

:param media_type: The media type to fetch 

:param username: The username for which to fetch the list 

:return: The list of List entries 

""" 

query = """ 

query($username: String, $type: MediaType) { 

MediaListCollection (userName: $username, type: $type) { 

lists { 

entries { 

""" + self.__media_list_entry_query + """ 

} 

} 

} 

} 

""" 

variables = {"username": username, "type": media_type.name} 

result = self.__graphql_query(query, variables) 

 

if result is None: 

return [] 

else: 

 

entries = [] 

entry_cls = MediaListEntry.get_class_for_media_type(media_type) 

 

for collection in result["MediaListCollection"]["lists"]: 

for entry in collection["entries"]: 

media_data = self.__generate_media_data( 

media_type, 

entry["media"] 

) 

user_data = self.__generate_media_user_data( 

media_type, 

entry 

) 

 

self.__cache_mal_to_anilist_map( 

media_type, 

media_data.id.get(IdType.MYANIMELIST), 

media_data.id.get(IdType.ANILIST) 

) 

 

entries.append(entry_cls(media_data, user_data)) 

return entries 

 

# Useful public methods --------------------------------------------------- 

 

def get_anilist_id_from_mal_id( 

self, 

media_type: MediaType, 

mal_id: int 

) -> Optional[int]: 

""" 

Retrieves an anilist ID from a myanimelist ID 

:param media_type: The media type of the myanimelist ID 

:param mal_id: The myanimelist ID 

:return: The anilist ID. May be None if myanimelist ID has no 

equivalent on anilist 

""" 

cached = self.cache.get_primitive( 

self.id_type, "mal-" + media_type.name + "-" + str(mal_id) 

) 

if cached is not None: 

return cached 

 

query = """ 

query ($mal_id: Int, $type: MediaType) { 

Media(idMal: $mal_id, type: $type) { 

id 

} 

} 

""" 

if mal_id is None: 

return None 

variables = {"mal_id": mal_id, "type": media_type.name} 

result = self.__graphql_query(query, variables) 

if result is None: 

return None 

else: 

anilist_id = result["Media"]["id"] 

self.__cache_mal_to_anilist_map(media_type, mal_id, anilist_id) 

return anilist_id 

 

# Helper Methods ---------------------------------------------------------- 

 

@staticmethod 

def __generate_media_user_data(media_type: MediaType, 

data: Dict[str, Any]) -> MediaUserData: 

""" 

Generates an Media User Data object from JSON data 

:param media_type: The media type to generate 

:param data: The data to parse as User Data 

:return: The generated MediaUserData object 

""" 

_id = Id({ 

IdType.ANILIST: data["media"]["id"], 

IdType.MYANIMELIST: data["media"]["idMal"] 

}) 

 

serialized = { 

"media_id": _id.serialize(), 

"media_type": media_type.name, 

"username": data["user"]["name"], 

"score": Score(data["score"], ScoreType.PERCENTAGE).serialize(), 

"consuming_status": data["status"], 

"episode_progress": data["progress"], 

"chapter_progress": data["progress"], 

"volume_progress": data["progressVolumes"] 

} 

 

for api_key, dict_key in { 

"startedAt": "consuming_start", 

"completedAt": "consuming_end" 

}.items(): 

try: 

serialized[dict_key] = Date( 

data[api_key]["year"], 

data[api_key]["month"], 

data[api_key]["day"] 

).serialize() 

except (TypeError, ValueError): 

serialized[dict_key] = None 

 

return MediaUserData.deserialize(serialized) 

 

# noinspection PyTypeChecker 

@staticmethod 

def __generate_media_data(media_type: MediaType, 

data: Dict[str, Any]) -> MediaData: 

""" 

Generates an MediaData object from a GraphQL result 

:param media_type: The media type to generate 

:param data: The data to convert into an AnimeData object 

:return: The generated AnimeData object 

""" 

_format = MediaFormat(data["format"]) 

_id = Id({ 

IdType.ANILIST: data["id"], 

IdType.MYANIMELIST: data["idMal"] 

}) 

 

title = Title({ 

TitleType.ROMAJI: data["title"]["romaji"], 

TitleType.ENGLISH: data["title"]["english"], 

TitleType.JAPANESE: data["title"]["native"], 

}) 

if title.get(TitleType.ENGLISH) is None: 

title.set(title.get(TitleType.ROMAJI), TitleType.ENGLISH) 

 

relations = [] 

for relation in data["relations"]["edges"]: 

dest_id = Id({ 

IdType.ANILIST: relation["node"]["id"], 

IdType.MYANIMELIST: relation["node"]["idMal"] 

}) 

dest_media_type = MediaType[relation["node"]["type"]] 

rel_type = RelationType[relation["relationType"]] 

 

if rel_type == RelationType.ADAPTATION: 

if media_type == MediaType.ANIME: 

dest_media_type = MediaType.MANGA 

else: 

dest_media_type = MediaType.ANIME 

 

relations.append(Relation( 

_id, media_type, dest_id, dest_media_type, rel_type 

).serialize()) 

 

# If no status is provided, use NOT_RELEASED per default 

releasing_status = data["status"] 

if releasing_status is None: 

releasing_status = "NOT_RELEASED" 

releasing_status = releasing_status\ 

.replace("NOT_YET_RELEASED", "NOT_RELEASED") 

 

serialized = { 

"media_type": media_type.name, 

"format": _format.name, 

"id": _id.serialize(), 

"title": title.serialize(), 

"relations": relations, 

"releasing_status": releasing_status, 

"cover_url": data["coverImage"]["large"], 

"episode_count": data["episodes"], 

"episode_duration": data["duration"], 

"chapter_count": data["episodes"], 

"volume_count": data["episodes"] 

} 

 

for api_key, dict_key in { 

"startDate": "releasing_start", 

"endDate": "releasing_end" 

}.items(): 

try: 

serialized[dict_key] = Date( 

data[api_key]["year"], 

data[api_key]["month"], 

data[api_key]["day"] 

).serialize() 

except (TypeError, ValueError): 

serialized[dict_key] = None 

 

return MediaData.deserialize(serialized) 

 

def __graphql_query(self, query: str, variables: Dict[str, Any]) \ 

-> Optional[Dict[str, Any]]: 

""" 

Executes a GraphQL query on the anilist API 

:param query: The query string 

:param variables: The variables to post 

:return: The result of the query or None if an error occured 

""" 

url = 'https://graphql.anilist.co' 

response = requests.post( 

url, json={'query': query, 'variables': variables} 

) 

time.sleep(self.rate_limit_pause) # For rate limiting 

result = json.loads(response.text) 

 

if "errors" in result: 

if result["errors"][0]["message"] == \ 

"Too Many Requests.": # pragma: no cover 

logging.getLogger(__name__).warning( 

"Rate limited on anilist. " 

"Waiting for 70 seconds before retrying" 

) 

time.sleep(70) 

return self.__graphql_query(query, variables) 

else: 

return None 

else: 

return result["data"] 

 

def __resolve_query_id(self, media_type: MediaType, _id: Id, 

allow_mal: bool) -> Optional[Tuple[int, IdType]]: 

""" 

Calculates the ID value to use in a query 

:param media_type: The media type of the ID 

:param _id: The ID 

:param allow_mal: If True, may return a Myanimelist ID. 

This will be signified by the second return value 

being IdType.MYANIMELIST 

:return: A tuple consisting of the ID and the IDs type 

""" 

mal_id = _id.get(IdType.MYANIMELIST) 

anilist_id = _id.get(IdType.ANILIST) 

 

id_type = IdType.ANILIST 

if anilist_id is None: 

query_id = mal_id 

 

if allow_mal: 

id_type = IdType.MYANIMELIST 

else: 

query_id = self.get_anilist_id_from_mal_id( 

media_type, query_id 

) 

 

else: 

query_id = anilist_id 

 

if query_id is None: 

return None 

else: 

return query_id, id_type 

 

def __cache_mal_to_anilist_map( 

self, 

media_type: MediaType, 

mal_id: int, 

anilist_id: int 

): 

""" 

Caches an anilist ID mapped to a myanimelist ID 

:param media_type: The media type to map 

:param mal_id: The myanimelist ID to map 

:param anilist_id: The anilist ID to map 

:return: None 

""" 

self.cache.add_primitive( 

self.id_type, 

"mal-" + media_type.name + "-" + str(mal_id), 

anilist_id 

) 

 

# Query definitions ------------------------------------------------------- 

 

__media_query = """ 

id 

idMal 

title { 

romaji 

english 

native 

} 

format 

status 

episodes 

duration 

coverImage { 

large 

} 

startDate { 

year 

month 

day 

} 

endDate { 

year 

month 

day 

} 

relations { 

edges { 

node { 

id 

idMal 

type 

} 

relationType 

} 

} 

""" 

""" 

The GraphQL query for a Media object 

""" 

 

__media_list_entry_query = """ 

user { 

name 

} 

score(format: POINT_100) 

status 

progress 

progressVolumes 

startedAt { 

year 

month 

day 

} 

completedAt { 

year 

month 

day 

} 

media { 

""" + __media_query + """ 

} 

""" 

""" 

The query for a media list entry 

"""