2024-08-20 09:08:40 +00:00
package api
import (
"fmt"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/database"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/models"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/services"
2024-10-27 05:13:40 +00:00
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
2024-08-20 09:08:40 +00:00
"github.com/gofiber/fiber/v2"
jsoniter "github.com/json-iterator/go"
"github.com/spf13/viper"
)
func createAttachmentDirectly ( c * fiber . Ctx ) error {
2024-10-27 05:13:40 +00:00
user := c . Locals ( "nex_user" ) . ( sec . UserInfo )
2024-08-20 09:08:40 +00:00
poolAlias := c . FormValue ( "pool" )
aliasingMap := viper . GetStringMapString ( "pools.aliases" )
if val , ok := aliasingMap [ poolAlias ] ; ok {
poolAlias = val
}
pool , err := services . GetAttachmentPoolByAlias ( poolAlias )
if err != nil {
return fiber . NewError ( fiber . StatusBadRequest , fmt . Sprintf ( "unable to get attachment pool info: %v" , err ) )
}
file , err := c . FormFile ( "file" )
if err != nil {
return err
}
2024-10-27 05:13:40 +00:00
if ! user . HasPermNode ( "CreateAttachments" , file . Size ) {
return fiber . NewError ( fiber . StatusForbidden , "you are not permitted to create attachments like this large" )
2024-08-20 09:08:40 +00:00
} else if pool . Config . Data ( ) . MaxFileSize != nil && file . Size > * pool . Config . Data ( ) . MaxFileSize {
return fiber . NewError ( fiber . StatusBadRequest , fmt . Sprintf ( "attachment pool %s doesn't allow file larger than %d" , pool . Alias , * pool . Config . Data ( ) . MaxFileSize ) )
}
usermeta := make ( map [ string ] any )
_ = jsoniter . UnmarshalFromString ( c . FormValue ( "metadata" ) , & usermeta )
tx := database . C . Begin ( )
metadata , err := services . NewAttachmentMetadata ( tx , user , file , models . Attachment {
Alternative : c . FormValue ( "alt" ) ,
MimeType : c . FormValue ( "mimetype" ) ,
Metadata : usermeta ,
IsMature : len ( c . FormValue ( "mature" ) ) > 0 ,
IsAnalyzed : false ,
2024-08-21 05:09:33 +00:00
IsUploaded : true ,
2024-08-20 09:08:40 +00:00
Destination : models . AttachmentDstTemporary ,
Pool : & pool ,
PoolID : & pool . ID ,
} )
if err != nil {
tx . Rollback ( )
return fiber . NewError ( fiber . StatusBadRequest , err . Error ( ) )
}
if err := services . UploadFileToTemporary ( c , file , metadata ) ; err != nil {
tx . Rollback ( )
return fiber . NewError ( fiber . StatusBadRequest , err . Error ( ) )
}
tx . Commit ( )
2024-10-27 05:13:40 +00:00
metadata . Account = models . Account { UserInfo : user }
2024-08-20 09:08:40 +00:00
metadata . Pool = & pool
services . PublishAnalyzeTask ( metadata )
return c . JSON ( metadata )
}