1- import { ShapeshiftJob , ShapeshiftJobStatus } from "../../types/Shapeshift" ;
2- import axios , { AxiosInstance } from "axios" ;
3- import { debugError } from "../../debug" ;
1+ import { ShapeshiftJob , ShapeshiftJobStatus } from "../../types/Shapeshift" ;
2+ import axios , { AxiosInstance } from "axios" ;
3+ import { debugError } from "../../debug" ;
4+ import Book from "../../models/book" ;
45
56export default class ShapeshiftService {
67 private instance : AxiosInstance ;
@@ -65,4 +66,38 @@ export default class ShapeshiftService {
6566 return emptyResponse ;
6667 }
6768 }
69+
70+ /**
71+ * Handle a webhook from Shapeshift to update the book's compilation status.
72+ * @param bookID - The ID of the book to update.
73+ * @param timestamp - The timestamp of the webhook event.
74+ * @returns - A string indicating the result of the operation: 'success', 'not_found', 'invalid_timestamp', or 'error'.
75+ */
76+ public async handleWebhook ( bookID : string , timestamp : number ) : Promise < 'success' | 'not_found' | 'invalid_timestamp' | 'error' > {
77+ try {
78+ const acceptedSkew = 5 * 60 * 1000 ; // 5 minutes in milliseconds
79+ const currentTime = Date . now ( ) ;
80+
81+ // Accept the webhook if the timestamp is plus or minus 5 minutes from the current time
82+ if ( Math . abs ( currentTime - timestamp ) > acceptedSkew ) {
83+ debugError ( `Timestamp for Shapeshift webhook is too skewed. Received: ${ timestamp } , Current: ${ currentTime } ` ) ;
84+ return 'invalid_timestamp' ;
85+ }
86+
87+ const book = await Book . updateOne ( { bookID : { $eq : bookID } } , {
88+ $set : { isCompiled : true } ,
89+ $max : { lastCompiled : timestamp } , // Only update lastCompiled if the new timestamp is greater than the existing value
90+ } ) ;
91+
92+ if ( ! book || book . matchedCount === 0 ) {
93+ debugError ( `Book with bookID ${ bookID } not found for Shapeshift webhook.` ) ;
94+ return 'not_found' ;
95+ }
96+
97+ return 'success' ;
98+ } catch ( error ) {
99+ debugError ( error ) ;
100+ return 'error' ;
101+ }
102+ }
68103}
0 commit comments