import { Post , PostList , CreatorData } from './CrawlResult.d' ; class API { static checkNumberGreater0 ( arg ) { let num = parseInt ( arg ) ; if ( ! isNaN ( num ) && num > 0 ) { return { result : true , value : num , } ; } return { result : false , value : 0 , } ; } static getURLSearchField ( url , query ) { const result = new URL ( url ) . searchParams . get ( query ) ; if ( result !== null ) { return encodeURIComponent ( result ) ; } else { return '' ; } } static getURLPathField ( query ) { const pathArr = location . pathname . split ( '/' ) ; const index = pathArr . indexOf ( query ) ; if ( index > 0 ) { return pathArr [ index + 1 ] ; } throw new Error ( `getURLPathField ${ query } failed!` ) ; } static assembleURL ( baseURL , args ) { const temp = new URL ( baseURL ) ; for ( const [ key , value ] of Object . entries ( args ) ) { value && temp . searchParams . append ( key , value . toString ( ) ) ; } return temp . toString ( ) ; } static request < T > ( url ) { return new Promise ( ( resolve , reject ) => { fetch ( url , { method : 'get' , credentials : 'include' , } ) . then ( ( response ) => { if ( response . ok ) { return response . json ( ) ; } else { reject ( { status : response . status , statusText : response . statusText , } ) ; } } ) . then ( ( data ) => { resolve ( data ) ; } ) . catch ( ( error ) => { reject ( error ) ; } ) ; } ) ; } static getCreatorId ( url ) { const split = url . split ( '/' ) ; for ( const str of split ) { if ( str . startsWith ( '@' ) ) { return str . split ( '@' ) [ 1 ] ; } } for ( const str of split ) { if ( str . endsWith ( '.fanbox.cc' ) ) { return str . split ( '.' ) [ 0 ] ; } } throw new Error ( 'GetCreatorId error!' ) ; } static async getUserId ( creatorId ) { const baseURL = `https://api.fanbox.cc/creator.get?creatorId=${ creatorId }` ; const res = ( await this . request ( baseURL ) ) as CreatorData ; return res . body . user . userId ; } static async getPostListSupporting ( limit = 10 , maxPublishedDatetime = '' , maxId = '' ) { const baseURL = 'https://api.fanbox.cc/post.listSupporting' ; const url = this . assembleURL ( baseURL , { limit , maxPublishedDatetime , maxId , } ) ; return this . request ( url ) ; } static async getPostListByUser ( creatorId , limit = 10 , maxPublishedDatetime = '' , maxId = '' ) { const baseURL = `https://api.fanbox.cc/post.listCreator?creatorId=${ creatorId }` ; const url = this . assembleURL ( baseURL , { limit , maxPublishedDatetime , maxId , } ) ; return this . request ( url ) ; } static async getTagPostListByUser ( userId , tag ) { const url = `https://api.fanbox.cc/post.listTagged?tag=${ tag }&userId=${ userId }` ; return this . request ( url ) ; } static async getPost ( postId ) { const url = `https://api.fanbox.cc/post.info?postId=${ postId }` ; return this . request ( url ) ; } } export { API } ;