@@ -8,10 +8,10 @@ class CdnUploadService
88 video/quicktime
99 ] . freeze
1010 MAX_FILE_SIZE = 50 . megabytes
11- CDN_API_TOKEN = "beans" . freeze
1211
1312 class UploadError < StandardError ; end
1413 class InvalidFileError < StandardError ; end
14+ class QuotaExceededError < StandardError ; end
1515
1616 def initialize ( file )
1717 @file = file
@@ -24,6 +24,10 @@ def upload!
2424
2525 private
2626
27+ def cdn_api_token
28+ Rails . application . credentials &.cdn || ENV [ "CDN" ]
29+ end
30+
2731 def validate_file!
2832 raise InvalidFileError , "No file provided" unless @file . present?
2933 raise InvalidFileError , "File too large (max 50MB)" if @file . size > MAX_FILE_SIZE
@@ -62,23 +66,32 @@ def validate_file_signature!
6266
6367 def upload_to_cdn
6468 @file . rewind
65- file_data = @file . read
66- base64_data = Base64 . strict_encode64 ( file_data )
67- data_url = "data:#{ @file . content_type } ;base64,#{ base64_data } "
68-
69- response = Faraday . post ( "https://cdn.hackclub.com/api/v3/new" ) do |req |
70- req . headers [ "Authorization" ] = "Bearer #{ CDN_API_TOKEN } "
71- req . headers [ "Content-Type" ] = "application/json"
72- req . body = [ data_url ] . to_json
73- end
74-
75- raise UploadError , "CDN upload failed: #{ response . status } " unless response . success?
7669
77- result = JSON . parse ( response . body )
78- files = result [ "files" ]
70+ conn = Faraday . new do |f |
71+ f . request :multipart
72+ f . adapter Faraday . default_adapter
73+ end
7974
80- raise UploadError , "No files returned from CDN" if files . blank?
75+ response = conn . post ( "https://cdn.hackclub.com/api/v4/upload" ) do |req |
76+ req . headers [ "Authorization" ] = "Bearer #{ cdn_api_token } "
77+ req . body = {
78+ file : Faraday ::Multipart ::FilePart . new (
79+ @file . tempfile ,
80+ @file . content_type ,
81+ @file . original_filename
82+ )
83+ }
84+ end
8185
82- files . first [ "deployedUrl" ]
86+ case response . status
87+ when 200 , 201
88+ result = JSON . parse ( response . body )
89+ result [ "url" ]
90+ when 402
91+ result = JSON . parse ( response . body )
92+ raise QuotaExceededError , "Storage quota exceeded: #{ result . dig ( 'quota' , 'percentage_used' ) } % used"
93+ else
94+ raise UploadError , "CDN upload failed: #{ response . status } "
95+ end
8396 end
8497end
0 commit comments