Coverage for otaku_info/routes/api/media_api.py: 46%

Shortcuts 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

27 statements  

1"""LICENSE 

2Copyright 2020 Hermann Krumrey <hermann@krumreyh.com> 

3 

4This file is part of otaku-info. 

5 

6otaku-info is free software: you can redistribute it and/or modify 

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

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

9(at your option) any later version. 

10 

11otaku-info is distributed in the hope that it will be useful, 

12but WITHOUT ANY WARRANTY; without even the implied warranty of 

13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14GNU General Public License for more details. 

15 

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

17along with otaku-info. If not, see <http://www.gnu.org/licenses/>. 

18LICENSE""" 

19 

20from typing import List 

21from flask.blueprints import Blueprint 

22from jerrycan.base import db 

23from jerrycan.routes.decorators import api 

24from jerrycan.exceptions import ApiException 

25from otaku_info.Config import Config 

26from otaku_info.db.MediaItem import MediaItem 

27from otaku_info.enums import MediaType, ListService 

28 

29 

30def define_blueprint(blueprint_name: str) -> Blueprint: 

31 """ 

32 Defines the blueprint for this route 

33 :param blueprint_name: The name of the blueprint 

34 :return: The blueprint 

35 """ 

36 blueprint = Blueprint(blueprint_name, __name__) 

37 api_base_path = f"/api/v{Config.API_VERSION}" 

38 

39 @blueprint.route( 

40 f"{api_base_path}/media_ids/<service>/<media_type>/<service_id>", 

41 methods=["GET"] 

42 ) 

43 @api 

44 def media_ids(service: str, media_type: str, service_id: str): 

45 """ 

46 Retrieves all media IDs for a media item 

47 :return: The IDs for the media item 

48 """ 

49 media_item: MediaItem = MediaItem.query.filter_by( 

50 service=ListService(service), 

51 media_type=MediaType(media_type), 

52 service_id=service_id 

53 ).first() 

54 if media_item is None: 

55 raise ApiException("ID does not exist", 404) 

56 

57 return {x.name: y.service_id for x, y in media_item.ids.items()} 

58 

59 @blueprint.route(f"{api_base_path}/id_mappings") 

60 def all_id_mappings(): 

61 """ 

62 Dumps all the ID mappings currently stored in the database 

63 :return: The ID Mappings 

64 """ 

65 all_items: List[MediaItem] = MediaItem.query.options( 

66 db.joinedload(MediaItem.id_mappings) 

67 ).all() 

68 

69 item_map = { 

70 x.name: {y.name: {} for y in MediaType} 

71 for x in ListService 

72 } 

73 for media_item in all_items: 

74 for service, mapping in media_item.ids.items(): 

75 item_map[service.name][media_item.media_type.name] = \ 

76 mapping.service_id 

77 

78 return {"mappings": item_map} 

79 

80 return blueprint