Commands.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. from Globals import Globals
  2. from Kobo import Kobo, KoboException
  3. import colorama
  4. import os
  5. class Commands:
  6. # It wasn't possible to format the main help message to my liking, so using a custom one.
  7. # This was the most annoying:
  8. #
  9. # commands:
  10. # command <-- absolutely unneeded text
  11. # get List unread books
  12. # list Get book
  13. #
  14. # See https://stackoverflow.com/questions/13423540/ and https://stackoverflow.com/questions/11070268/
  15. @staticmethod
  16. def ShowUsage():
  17. usage = \
  18. """Kobo book downloader and DRM remover
  19. Usage:
  20. kobo-book-downloader [--help] command ...
  21. Commands:
  22. get Download book
  23. info Show the location of the configuration file
  24. list List your books
  25. Optional arguments:
  26. -h, --help Show this help message and exit
  27. Examples:
  28. kobo-book-downloader get /dir/book.epub 01234567-89ab-cdef-0123-456789abcdef Download book
  29. kobo-book-downloader get /dir/ 01234567-89ab-cdef-0123-456789abcdef Download book and name the file automatically
  30. kobo-book-downloader get /dir/ --all Download all your books
  31. kobo-book-downloader info Show the location of the program's configuration file
  32. kobo-book-downloader list List your unread books
  33. kobo-book-downloader list --all List all your books
  34. kobo-book-downloader list --help Get additional help for the list command (it works for get too)"""
  35. print( usage )
  36. @staticmethod
  37. def __GetBookAuthor( book: dict ) -> str:
  38. contributors = book.get( "ContributorRoles" )
  39. authors = []
  40. for contributor in contributors:
  41. role = contributor.get( "Role" )
  42. if role == "Author":
  43. authors.append( contributor[ "Name" ] )
  44. # Unfortunately the role field is not filled out in the data returned by the "library_sync" endpoint, so we only
  45. # use the first author and hope for the best. Otherwise we would get non-main authors too. For example Christopher
  46. # Buckley beside Joseph Heller for the -- terrible -- novel Catch-22.
  47. if len( authors ) == 0 and len( contributors ) > 0:
  48. authors.append( contributors[ 0 ][ "Name" ] )
  49. return " & ".join( authors )
  50. @staticmethod
  51. def __SanitizeFileName( fileName: str ) -> str:
  52. result = ""
  53. for c in fileName:
  54. if c.isalnum() or " ,;.!(){}[]#$'-+@_".find( c ) >= 0:
  55. result += c
  56. result = result.strip( " ." )
  57. result = result[ :100 ] # Limit the length -- mostly because of Windows. It would be better to do it on the full path using MAX_PATH.
  58. return result
  59. @staticmethod
  60. def __MakeFileNameForBook( book: dict ) -> str:
  61. fileName = ""
  62. author = Commands.__GetBookAuthor( book )
  63. if len( author ) > 0:
  64. fileName = author + " - "
  65. fileName += book[ "Title" ]
  66. fileName = Commands.__SanitizeFileName( fileName )
  67. fileName += ".epub"
  68. return fileName
  69. @staticmethod
  70. def __IsBookArchived( newEntitlement: dict ) -> bool:
  71. bookEntitlement = newEntitlement.get( "BookEntitlement" )
  72. if bookEntitlement is None:
  73. return False
  74. isRemoved = bookEntitlement.get( "IsRemoved" )
  75. if isRemoved is None:
  76. return False
  77. return isRemoved
  78. @staticmethod
  79. def __GetBook( revisionId: str, outputPath: str ) -> None:
  80. if os.path.isdir( outputPath ):
  81. book = Globals.Kobo.GetBookInfo( revisionId )
  82. fileName = Commands.__MakeFileNameForBook( book )
  83. outputPath = os.path.join( outputPath, fileName )
  84. else:
  85. parentPath = os.path.dirname( outputPath )
  86. if not os.path.isdir( parentPath ):
  87. raise KoboException( "The parent directory ('%s') of the output file must exist." % parentPath )
  88. print( "Downloading book to '%s'." % outputPath )
  89. Globals.Kobo.Download( revisionId, Kobo.DisplayProfile, outputPath )
  90. @staticmethod
  91. def __GetAllBooks( outputPath: str ) -> None:
  92. if not os.path.isdir( outputPath ):
  93. raise KoboException( "The output path must be a directory when downloading all books." )
  94. bookList = Globals.Kobo.GetMyBookList()
  95. for entitlement in bookList:
  96. newEntitlement = entitlement.get( "NewEntitlement" )
  97. if newEntitlement is None:
  98. continue
  99. bookMetadata = newEntitlement[ "BookMetadata" ]
  100. fileName = Commands.__MakeFileNameForBook( bookMetadata )
  101. outputFilePath = os.path.join( outputPath, fileName )
  102. # Skip archived books.
  103. if Commands.__IsBookArchived( newEntitlement ):
  104. title = bookMetadata[ "Title" ]
  105. author = Commands.__GetBookAuthor( bookMetadata )
  106. if len( author ) > 0:
  107. title += " by " + author
  108. print( colorama.Fore.LIGHTYELLOW_EX + ( "Skipping archived book %s." % title ) + colorama.Fore.RESET )
  109. continue
  110. print( "Downloading book to '%s'." % outputFilePath )
  111. Globals.Kobo.Download( bookMetadata[ "RevisionId" ], Kobo.DisplayProfile, outputFilePath )
  112. @staticmethod
  113. def GetBookOrBooks( revisionId: str, outputPath: str, getAll: bool ) -> None:
  114. revisionIdIsSet = ( revisionId is not None ) and len( revisionId ) > 0
  115. if getAll:
  116. if revisionIdIsSet:
  117. raise KoboException( "Got unexpected book identifier parameter ('%s')." % revisionId )
  118. Commands.__GetAllBooks( outputPath )
  119. else:
  120. if not revisionIdIsSet:
  121. raise KoboException( "Missing book identifier parameter. Did you mean to use the --all parameter?" )
  122. Commands.__GetBook( revisionId, outputPath )
  123. @staticmethod
  124. def __IsBookRead( newEntitlement: dict ) -> bool:
  125. readingState = newEntitlement.get( "ReadingState" )
  126. if readingState is None:
  127. return False
  128. statusInfo = readingState.get( "StatusInfo" )
  129. if statusInfo is None:
  130. return False
  131. status = statusInfo.get( "Status" )
  132. return status == "Finished"
  133. @staticmethod
  134. def ListBooks( listAll: bool ) -> None:
  135. colorama.init()
  136. bookList = Globals.Kobo.GetMyBookList()
  137. rows = []
  138. for entitlement in bookList:
  139. newEntitlement = entitlement.get( "NewEntitlement" )
  140. if newEntitlement is None:
  141. continue
  142. if ( not listAll ) and Commands.__IsBookRead( newEntitlement ):
  143. continue
  144. bookMetadata = newEntitlement[ "BookMetadata" ]
  145. book = [ bookMetadata[ "RevisionId" ],
  146. bookMetadata[ "Title" ],
  147. Commands.__GetBookAuthor( bookMetadata ),
  148. Commands.__IsBookArchived( newEntitlement ) ]
  149. rows.append( book )
  150. rows = sorted( rows, key = lambda columns: columns[ 1 ].lower() )
  151. for columns in rows:
  152. revisionId = colorama.Style.DIM + columns[ 0 ] + colorama.Style.RESET_ALL
  153. title = colorama.Style.BRIGHT + columns[ 1 ] + colorama.Style.RESET_ALL
  154. author = columns[ 2 ]
  155. if len( author ) > 0:
  156. title += " by " + author
  157. archived = columns[ 3 ]
  158. if archived:
  159. title += colorama.Fore.LIGHTYELLOW_EX + " (archived)" + colorama.Fore.RESET
  160. print( "%s \t %s" % ( revisionId, title ) )
  161. @staticmethod
  162. def Info():
  163. print( "The configuration file is located at:\n%s" % Globals.Settings.SettingsFilePath )