diff --git a/cmd/cli-uploader/cliapi/cliapi.go b/cmd/cli-uploader/cliapi/cliapi.go index 4802392d..b377cb0c 100644 --- a/cmd/cli-uploader/cliapi/cliapi.go +++ b/cmd/cli-uploader/cliapi/cliapi.go @@ -83,23 +83,25 @@ func GetVersion() (string, int, error) { return parsedResult.Version, parsedResult.VersionInt, nil } -// GetConfig returns the upload configuration of the Gokapi server -func GetConfig() (int, int, bool, error) { +// GetConfig returns the upload configuration of the Gokapi server: the maximum file size, the chunk size, +// whether end-to-end encryption is enabled and the maximum expiry in seconds (0 if unlimited) +func GetConfig() (int, int, bool, int64, error) { result, err := getUrl(gokapiUrl+"/info/config", []header{}, false) if err != nil { - return 0, 0, false, err + return 0, 0, false, 0, err } type expectedFormat struct { MaxFilesize int MaxChunksize int + MaxExpirySeconds int64 EndToEndEncryptionEnabled bool } var parsedResult expectedFormat err = json.Unmarshal([]byte(result), &parsedResult) if err != nil { - return 0, 0, false, err + return 0, 0, false, 0, err } - return parsedResult.MaxFilesize, parsedResult.MaxChunksize, parsedResult.EndToEndEncryptionEnabled, nil + return parsedResult.MaxFilesize, parsedResult.MaxChunksize, parsedResult.EndToEndEncryptionEnabled, parsedResult.MaxExpirySeconds, nil } func stripApiKeyOnRedirect(req *http.Request, via []*http.Request) error { @@ -159,7 +161,7 @@ func UploadFile(uploadParams cliflags.FlagConfig) (models.FileApiOutput, error) os.Exit(4) } defer file.Close() - maxSize, chunkSize, isE2e, err := GetConfig() + maxSize, chunkSize, isE2e, maxExpirySeconds, err := GetConfig() if err != nil { return models.FileApiOutput{}, err } @@ -200,7 +202,7 @@ func UploadFile(uploadParams cliflags.FlagConfig) (models.FileApiOutput, error) return models.FileApiOutput{}, err } } - metaData, err := completeChunk(uuid, "Encrypted File", sizeBytes, realSize, true, uploadParams, progressBar) + metaData, err := completeChunk(uuid, "Encrypted File", sizeBytes, realSize, true, uploadParams, maxExpirySeconds, progressBar) if err != nil { return models.FileApiOutput{}, err } @@ -227,7 +229,7 @@ func UploadFile(uploadParams cliflags.FlagConfig) (models.FileApiOutput, error) return models.FileApiOutput{}, err } } - metaData, err := completeChunk(uuid, nameToBase64(file, uploadParams), sizeBytes, realSize, false, uploadParams, progressBar) + metaData, err := completeChunk(uuid, nameToBase64(file, uploadParams), sizeBytes, realSize, false, uploadParams, maxExpirySeconds, progressBar) if err != nil { return models.FileApiOutput{}, err } @@ -470,7 +472,7 @@ func uploadChunk(f io.Reader, uuid string, offset, chunkSize, filesize int64, pr return nil } -func completeChunk(uid, filename string, filesize, realsize int64, useE2e bool, uploadParams cliflags.FlagConfig, progressBar *progressbar.ProgressBar) (models.FileApiOutput, error) { +func completeChunk(uid, filename string, filesize, realsize int64, useE2e bool, uploadParams cliflags.FlagConfig, maxExpirySeconds int64, progressBar *progressbar.ProgressBar) (models.FileApiOutput, error) { type expectedFormat struct { FileInfo models.FileApiOutput `json:"FileInfo"` } @@ -480,17 +482,20 @@ func completeChunk(uid, filename string, filesize, realsize int64, useE2e bool, if !uploadParams.JsonOutput { fmt.Println("Finalising...") } - result, err := getUrl(gokapiUrl+"/chunk/complete", []header{ + headers := []header{ {"uuid", uid}, {"filename", filename}, {"filesize", strconv.FormatInt(filesize, 10)}, {"realsize", strconv.FormatInt(realsize, 10)}, {"isE2E", strconv.FormatBool(useE2e)}, {"allowedDownloads", strconv.Itoa(uploadParams.ExpiryDownloads)}, - {"expiryDays", strconv.Itoa(uploadParams.ExpiryDays)}, {"password", uploadParams.Password}, {"contenttype", "application/octet-stream"}, - }, true) + } + if isExpiryHeaderRequired(uploadParams, maxExpirySeconds) { + headers = append(headers, header{"expiryDays", strconv.Itoa(uploadParams.ExpiryDays)}) + } + result, err := getUrl(gokapiUrl+"/chunk/complete", headers, true) if err != nil { return models.FileApiOutput{}, err } @@ -502,6 +507,12 @@ func completeChunk(uid, filename string, filesize, realsize int64, useE2e bool, return parsedResult.FileInfo, nil } +// isExpiryHeaderRequired returns false if the server limits the expiry and the user did not set one, +// so that the server's default applies instead of the CLI's default of unlimited, which would be refused +func isExpiryHeaderRequired(uploadParams cliflags.FlagConfig, maxExpirySeconds int64) bool { + return maxExpirySeconds == 0 || uploadParams.IsExpiryDaysSet +} + func lockUnlockE2eLock(isUnlock bool) error { var url = gokapiUrl + "/e2e/mutex/lock" if isUnlock { diff --git a/cmd/cli-uploader/cliapi/cliapi_test.go b/cmd/cli-uploader/cliapi/cliapi_test.go new file mode 100644 index 00000000..3f6c86d0 --- /dev/null +++ b/cmd/cli-uploader/cliapi/cliapi_test.go @@ -0,0 +1,40 @@ +//go:build test + +package cliapi + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/forceu/gokapi/cmd/cli-uploader/cliflags" + "github.com/forceu/gokapi/internal/test" +) + +func TestCompleteChunkExpiryHeader(t *testing.T) { + var receivedHeaders http.Header + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + receivedHeaders = r.Header.Clone() + _, _ = w.Write([]byte(`{"Result":"OK","FileInfo":{}}`)) + })) + defer server.Close() + Init(server.URL, "apikey", nil) + + testCases := []struct { + name string + params cliflags.FlagConfig + maxExpirySeconds int64 + expectedHeader []string + }{ + {"no server limit, flag not set", cliflags.FlagConfig{}, 0, []string{"0"}}, + {"no server limit, flag set", cliflags.FlagConfig{ExpiryDays: 5, IsExpiryDaysSet: true}, 0, []string{"5"}}, + {"server limit, flag not set", cliflags.FlagConfig{}, 3600, nil}, + {"server limit, flag set", cliflags.FlagConfig{ExpiryDays: 0, IsExpiryDaysSet: true}, 3600, []string{"0"}}, + } + for _, tc := range testCases { + tc.params.JsonOutput = true + _, err := completeChunk("uuid", "file", 1, 1, false, tc.params, tc.maxExpirySeconds, nil) + test.IsNilWithMessage(t, err, tc.name) + test.IsEqual(t, receivedHeaders.Values("expiryDays"), tc.expectedHeader) + } +} diff --git a/cmd/cli-uploader/cliconfig/cliconfig.go b/cmd/cli-uploader/cliconfig/cliconfig.go index 2e77e199..e5c34240 100644 --- a/cmd/cli-uploader/cliconfig/cliconfig.go +++ b/cmd/cli-uploader/cliconfig/cliconfig.go @@ -75,7 +75,7 @@ func CreateLogin() { } fmt.Print("OK\nDownloading configuration...") - _, _, isE2E, err := cliapi.GetConfig() + _, _, isE2E, _, err := cliapi.GetConfig() if err != nil { fmt.Println("FAIL") if errors.Is(err, cliapi.ErrUnauthorised) { diff --git a/cmd/cli-uploader/cliflags/cliflags.go b/cmd/cli-uploader/cliflags/cliflags.go index 653a9e0d..e873f762 100644 --- a/cmd/cli-uploader/cliflags/cliflags.go +++ b/cmd/cli-uploader/cliflags/cliflags.go @@ -43,6 +43,7 @@ type FlagConfig struct { ExpiryDays int ExpiryDownloads int Password string + IsExpiryDaysSet bool } // Parse parses the command line arguments and returns the mode. @@ -91,6 +92,7 @@ func GetUploadParameters(mode int) FlagConfig { fallthrough case "--expiry-days": result.ExpiryDays = requireInt(getParameter(&i)) + result.IsExpiryDaysSet = true case "-d": fallthrough case "--expiry-downloads": @@ -296,7 +298,7 @@ func printUsage(exitCode int) { fmt.Println(" -c, --configuration Path to configuration file (default: gokapi-cli.json)") fmt.Println(" -j, --json Output the result in JSON only") fmt.Println(" -x, --disable-e2e Disable end-to-end encryption") - fmt.Println(" -e, --expiry-days Set file expiry in days (default: unlimited)") + fmt.Println(" -e, --expiry-days Set file expiry in days (default: unlimited, or the server's maximum if set)") fmt.Println(" -d, --expiry-downloads Set max allowed downloads (default: unlimited)") fmt.Println(" -p, --password Set a password for the file") fmt.Println(" -n, --name Change final filename for uploaded file") diff --git a/cmd/cli-uploader/cliflags/cliflags_test.go b/cmd/cli-uploader/cliflags/cliflags_test.go new file mode 100644 index 00000000..c03ecb15 --- /dev/null +++ b/cmd/cli-uploader/cliflags/cliflags_test.go @@ -0,0 +1,30 @@ +//go:build test + +package cliflags + +import ( + "os" + "testing" + + "github.com/forceu/gokapi/internal/test" +) + +func TestGetUploadParametersExpiryDays(t *testing.T) { + originalArgs := os.Args + defer func() { os.Args = originalArgs }() + + os.Args = []string{"gokapi-cli", "upload", "-f", "file"} + result := GetUploadParameters(ModeUpload) + test.IsEqualInt(t, result.ExpiryDays, 0) + test.IsEqualBool(t, result.IsExpiryDaysSet, false) + + os.Args = []string{"gokapi-cli", "upload", "-f", "file", "--expiry-days", "0"} + result = GetUploadParameters(ModeUpload) + test.IsEqualInt(t, result.ExpiryDays, 0) + test.IsEqualBool(t, result.IsExpiryDaysSet, true) + + os.Args = []string{"gokapi-cli", "upload", "-f", "file", "-e", "7"} + result = GetUploadParameters(ModeUpload) + test.IsEqualInt(t, result.ExpiryDays, 7) + test.IsEqualBool(t, result.IsExpiryDaysSet, true) +} diff --git a/docs/advanced.rst b/docs/advanced.rst index 5d518954..f6dabfb5 100644 --- a/docs/advanced.rst +++ b/docs/advanced.rst @@ -106,6 +106,18 @@ Available environment variables +-------------------------------------+----------------------------------------------------------------------------------------------------------+-----------------+-----------------------------+ | GOKAPI_LOG_STDOUT | Also outputs all log file entries to the console output, if set to true | No | false | +-------------------------------------+----------------------------------------------------------------------------------------------------------+-----------------+-----------------------------+ +| GOKAPI_MAX_EXPIRY_SECONDS | Sets the maximum time in seconds that a file is stored before it expires | No | 0 | +| | | | | +| | Applies to all users including admins: uploads, file request uploads, edits, | | | +| | | | | +| | duplicates and file request links. A longer or unlimited expiry is refused, the | | | +| | | | | +| | default expiry is reduced to this value and files uploaded through file requests | | | +| | | | | +| | expire after this time | | | +| | | | | +| | Set to 0 to disable the limit | | | ++-------------------------------------+----------------------------------------------------------------------------------------------------------+-----------------+-----------------------------+ | GOKAPI_MAX_FILESIZE | Sets the maximum allowed file size in MB | Yes | 102400 | | | | | | | | Default 102400 = 100GB | | | diff --git a/docs/usage.rst b/docs/usage.rst index ea8ff3e3..85acd80f 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -16,7 +16,7 @@ After you have started the Gokapi server, log in with your credentials by going There you can list and manage files and upload new files. You will also see three fields: - *Allowed downloads* lets you set how many times a file can be downloaded before it gets deleted - - *Expiry in days* lets you set after how many days a file gets deleted latest + - *Expiry in days* lets you set after how many days a file gets deleted latest. If the server sets a maximum lifetime with ``GOKAPI_MAX_EXPIRY_SECONDS``, files cannot be stored for longer or without a time limit, and files uploaded through file requests expire after that time - *Password* lets you set a password that a user needs to enter before downloading the file. Please note that the file on the storage server is not encrypted. Uploading new files @@ -116,7 +116,7 @@ To create a new request, click the *Plus* icon at the top right. To modify an ex * - **Max Size** - Set a maximum total size (in MB) for the entire request. * - **Expiry** - - Set a date after which the link will no longer function. + - Set a date after which the link will no longer function. If the server sets a maximum lifetime with ``GOKAPI_MAX_EXPIRY_SECONDS``, the date cannot be later than that and the link cannot be kept without an expiry. * - **Notes** - Public notes that are shown on the upload page diff --git a/internal/environment/Environment.go b/internal/environment/Environment.go index 1a238a6a..793c43cd 100644 --- a/internal/environment/Environment.go +++ b/internal/environment/Environment.go @@ -60,6 +60,13 @@ type Environment struct { // for all users // Default 10240 = 10GB MaxSizeGuestUploadMb int `env:"MAX_SIZE_GUESTUPLOAD" envDefault:"10240" onlyPositive:"true"` + // Sets the maximum time in seconds that a file is stored before it expires + // Applies to all users including admins: uploads, file request uploads, edits, + // duplicates and file request links. A longer or unlimited expiry is refused, the + // default expiry is reduced to this value and files uploaded through file requests + // expire after this time + // Set to 0 to disable the limit + MaxExpirySeconds int64 `env:"MAX_EXPIRY_SECONDS" envDefault:"0" onlyPositive:"true"` // Set the number of chunks that are uploaded in parallel for a single file MaxParallelUploads int `env:"MAX_PARALLEL_UPLOADS" envDefault:"3" onlyPositive:"true" persistent:"true"` // Sets the minimum free space on the disk in MB for accepting an upload diff --git a/internal/environment/Environment_test.go b/internal/environment/Environment_test.go index 06ba9515..4473f043 100644 --- a/internal/environment/Environment_test.go +++ b/internal/environment/Environment_test.go @@ -64,6 +64,18 @@ func TestEnvLoad(t *testing.T) { os.Unsetenv("GOKAPI_MAX_FILESIZE") } +func TestMaxExpirySeconds(t *testing.T) { + env := New() + test.IsEqualInt64(t, env.MaxExpirySeconds, 0) + os.Setenv("GOKAPI_MAX_EXPIRY_SECONDS", "3600") + env = New() + test.IsEqualInt64(t, env.MaxExpirySeconds, 3600) + os.Setenv("GOKAPI_MAX_EXPIRY_SECONDS", "-5") + env = New() + test.IsEqualInt64(t, env.MaxExpirySeconds, 0) + os.Unsetenv("GOKAPI_MAX_EXPIRY_SECONDS") +} + func TestIsAwsProvided(t *testing.T) { os.Unsetenv("GOKAPI_AWS_BUCKET") os.Unsetenv("GOKAPI_AWS_REGION") diff --git a/internal/webserver/Webserver.go b/internal/webserver/Webserver.go index d3f04a86..24b7ce22 100644 --- a/internal/webserver/Webserver.go +++ b/internal/webserver/Webserver.go @@ -799,6 +799,7 @@ type AdminView struct { CpuLoad int MemoryUsagePercent int DiskUsagePercent int + MaxExpirySeconds int64 DataServed int64 Uptime int64 TimeNow int64 @@ -929,6 +930,7 @@ func (u *AdminView) convertGlobalConfig(view int, user models.User) *AdminView { u.IsAdminView = true u.ActiveView = view u.MaxFileSize = config.MaxFileSizeMB + u.MaxExpirySeconds = configuration.GetEnvironment().MaxExpirySeconds u.IsLogoutAvailable = authentication.IsLogoutAvailable() u.ShowApiMenu = showApiMenu u.IsUserTabAvailable = config.Authentication.Method != models.AuthenticationDisabled diff --git a/internal/webserver/api/Api.go b/internal/webserver/api/Api.go index b646e932..8c99a99a 100644 --- a/internal/webserver/api/Api.go +++ b/internal/webserver/api/Api.go @@ -102,6 +102,13 @@ func apiEditFile(w http.ResponseWriter, r requestParser, user models.User, _ mod sendError(w, http.StatusUnauthorized, errorcodes.NoPermission, "No permission to edit file.") return } + if request.UnlimitedExpiry || request.ExpiryTimestamp != 0 { + err := fileupload.CheckMaxExpiry(request.UnlimitedExpiry, request.ExpiryTimestamp) + if err != nil { + sendError(w, http.StatusBadRequest, errorcodes.ExpiryTooLong, err.Error()) + return + } + } if request.UnlimitedDownloads { file.UnlimitedDownloads = true } else { @@ -514,6 +521,15 @@ func apiChunkComplete(w http.ResponseWriter, r requestParser, user models.User, request.IsE2E, request.FileSize, "") + if request.IsExpirySet { + err := fileupload.CheckMaxExpiry(uploadParams.UnlimitedTime, uploadParams.ExpiryTimestamp) + if err != nil { + sendError(w, http.StatusBadRequest, errorcodes.ExpiryTooLong, err.Error()) + return + } + } else { + fileupload.CapToMaxExpiry(&uploadParams) + } if request.IsNonBlocking { doNonBlockingPartCompleteChunk(nil, request.Uuid, request.FileHeader, user, uploadParams) _, _ = io.WriteString(w, "{\"result\":\"OK\"}") @@ -568,6 +584,7 @@ func apiChunkUploadRequestComplete(w http.ResponseWriter, r requestParser, user sendError(w, http.StatusBadRequest, errorcodes.FileTooLarge, storage.ErrorFileTooLarge.Error()) return } + fileupload.CapToMaxExpiry(&uploadParams) if request.IsNonBlocking { doNonBlockingPartCompleteChunk(nil, request.Uuid, request.FileHeader, user, uploadParams) _, _ = io.WriteString(w, "{\"result\":\"OK\"}") @@ -589,12 +606,14 @@ func apiConfigInfo(w http.ResponseWriter, _ requestParser, _ models.User, _ mode type configInfo struct { MaxFilesize int MaxChunksize int + MaxExpirySeconds int64 EndToEndEncryptionEnabled bool } config := configuration.Get() result, err := json.Marshal(configInfo{ MaxFilesize: config.MaxFileSizeMB, MaxChunksize: config.ChunkSize, + MaxExpirySeconds: configuration.GetEnvironment().MaxExpirySeconds, EndToEndEncryptionEnabled: config.Encryption.Level == encryption.EndToEndEncryption, }) helper.Check(err) @@ -774,6 +793,10 @@ func apiUploadFile(w http.ResponseWriter, r requestParser, user models.User, _ m request.Request.Body = http.MaxBytesReader(w, request.Request.Body, maxUpload) err := fileupload.ProcessCompleteFile(w, request.Request, user.Id, configuration.Get().MaxMemory) + if errors.Is(err, fileupload.ErrorExpiryTooLong) { + sendError(w, http.StatusBadRequest, errorcodes.ExpiryTooLong, err.Error()) + return + } if err != nil { sendError(w, http.StatusBadRequest, errorcodes.UnspecifiedError, err.Error()) return @@ -803,6 +826,20 @@ func apiDuplicateFile(w http.ResponseWriter, r requestParser, user models.User, 0, // is not being used by storage.DuplicateFile "") uploadConfig.UserId = user.Id + if request.RequestedChanges&storage.ParamExpiry != 0 { + err := fileupload.CheckMaxExpiry(uploadConfig.UnlimitedTime, uploadConfig.ExpiryTimestamp) + if err != nil { + sendError(w, http.StatusBadRequest, errorcodes.ExpiryTooLong, err.Error()) + return + } + } else { + err := fileupload.CheckMaxExpiry(file.UnlimitedTime, file.ExpireAt) + if err != nil { + sendError(w, http.StatusBadRequest, errorcodes.ExpiryTooLong, + "expiry of the original file: "+err.Error()+", expiryDays has to be set") + return + } + } newFile, err := storage.DuplicateFile(file, request.RequestedChanges, request.FileName, uploadConfig) if err != nil { sendError(w, http.StatusInternalServerError, errorcodes.InternalServer, err.Error()) @@ -1265,6 +1302,13 @@ func apiURequestSave(w http.ResponseWriter, r requestParser, user models.User, _ " or values larger than the server's max size / file count") return } + if request.IsExpirySet { + err := fileupload.CheckMaxExpiry(request.Expiry == 0, request.Expiry) + if err != nil { + sendError(w, http.StatusBadRequest, errorcodes.ExpiryTooLong, err.Error()) + return + } + } if !isNewRequest { uploadRequest, ok = database.GetFileRequest(request.Id) @@ -1291,6 +1335,8 @@ func apiURequestSave(w http.ResponseWriter, r requestParser, user models.User, _ } if request.IsExpirySet { uploadRequest.Expiry = request.Expiry + } else if isNewRequest { + uploadRequest.Expiry = fileupload.DefaultFileRequestExpiry() } if request.IsMaxFilesSet { uploadRequest.MaxFiles = request.MaxFiles diff --git a/internal/webserver/api/Api_test.go b/internal/webserver/api/Api_test.go index 61f58434..0b7bd98c 100644 --- a/internal/webserver/api/Api_test.go +++ b/internal/webserver/api/Api_test.go @@ -19,6 +19,7 @@ import ( "github.com/forceu/gokapi/internal/helper" "github.com/forceu/gokapi/internal/models" "github.com/forceu/gokapi/internal/storage" + "github.com/forceu/gokapi/internal/storage/filerequest" "github.com/forceu/gokapi/internal/test" "github.com/forceu/gokapi/internal/test/testconfiguration" "github.com/forceu/gokapi/internal/webserver/ratelimiter" @@ -1870,3 +1871,318 @@ func TestChunkCompleteSanitisationUnit(t *testing.T) { test.IsEqualBool(t, strings.Contains(p.FileHeader.Filename, "\r"), false) test.IsEqualBool(t, strings.Contains(p.FileHeader.Filename, "\n"), false) } + +const responseExpiryTooLong = `{"Result":"error","ErrorMessage":"expiry exceeds the server's maximum of 3600 seconds","ErrorCode":20}` + +// setMaxExpiry sets GOKAPI_MAX_EXPIRY_SECONDS for the duration of the test +func setMaxExpiry(t *testing.T, seconds string) { + t.Helper() + test.IsNil(t, os.Setenv("GOKAPI_MAX_EXPIRY_SECONDS", seconds)) + configuration.Load() + t.Cleanup(func() { + _ = os.Unsetenv("GOKAPI_MAX_EXPIRY_SECONDS") + configuration.Load() + }) +} + +// isInSecondsFromNow returns true if timestamp is now + seconds, allowing for the time the test took +func isInSecondsFromNow(timestamp, seconds int64) bool { + expected := time.Now().Unix() + seconds + return timestamp >= expected-2 && timestamp <= expected +} + +// createTestChunk stores a chunk with a size of 13 bytes, as if it had been uploaded +func createTestChunk(t *testing.T, uuid string) { + t.Helper() + err := os.WriteFile(configuration.Get().DataDir+"/chunk-"+uuid, []byte("chunktestfile"), 0600) + test.IsNil(t, err) +} + +// getFileInfo parses a response containing a models.Result +func getFileInfo(t *testing.T, w *httptest.ResponseRecorder) models.FileApiOutput { + t.Helper() + var result models.Result + err := json.Unmarshal(w.Body.Bytes(), &result) + test.IsNil(t, err) + return result.FileInfo +} + +// saveTestFile stores a file, which expires at expireAt or never if expireAt is 0 +func saveTestFile(id string, expireAt int64) models.File { + file := models.File{ + Id: id, + Name: id + "Name", + SHA1: "e017693e4a04a59d0b0f400fe98177fe7ee13cf7", + ExpireAt: expireAt, + UnlimitedDownloads: true, + UnlimitedTime: expireAt == 0, + UserId: idSuperAdmin, + } + database.SaveMetaData(file) + return file +} + +func TestMaxExpiryChunkComplete(t *testing.T) { + // The limit also applies to admins + apiKey := generateNewKey(true, idSuperAdmin, "", "") + apiKey.GrantPermission(models.ApiPermUpload) + database.SaveApiKey(apiKey) + headers := []test.Header{ + {Name: "uuid", Value: "maxexpirychunk"}, + {Name: "filename", Value: "maxexpiry.upload"}, + {Name: "filesize", Value: "13"}} + + setMaxExpiry(t, "3600") + createTestChunk(t, "maxexpirychunk") + for _, expiryDays := range []string{"0", "30", "100001"} { + w, r := getRecorder("/chunk/complete", apiKey.Id, append(headers, test.Header{Name: "expiryDays", Value: expiryDays})) + Process(w, r) + test.IsEqualInt(t, w.Code, 400) + test.ResponseBodyIs(t, w, responseExpiryTooLong) + } + w, r := getRecorder("/chunk/complete", apiKey.Id, headers) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + file := getFileInfo(t, w) + test.IsEqualBool(t, file.UnlimitedTime, false) + test.IsEqualBool(t, isInSecondsFromNow(file.ExpireAt, 3600), true) + + // An expiry of exactly the limit is accepted + setMaxExpiry(t, "86400") + createTestChunk(t, "maxexpirychunk") + w, r = getRecorder("/chunk/complete", apiKey.Id, append(headers, test.Header{Name: "expiryDays", Value: "1"})) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualBool(t, isInSecondsFromNow(getFileInfo(t, w).ExpireAt, 86400), true) + + // A limit longer than the default expiry of 14 days keeps the default + setMaxExpiry(t, "2592000") + createTestChunk(t, "maxexpirychunk") + w, r = getRecorder("/chunk/complete", apiKey.Id, headers) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualBool(t, isInSecondsFromNow(getFileInfo(t, w).ExpireAt, 14*24*3600), true) +} + +func uploadFileWithExpiry(t *testing.T, apiKey, expiryDays string) *httptest.ResponseRecorder { + var postValues []test.PostBody + if expiryDays != "" { + postValues = append(postValues, test.PostBody{Key: "expiryDays", Value: expiryDays}) + } + body, contentType := test.FileToMultipartFormBody(t, test.HttpTestConfig{ + UploadFileName: "test/fileupload.jpg", + UploadFieldName: "file", + PostValues: postValues, + }) + w, r := getRecorderWithBody("/files/add", apiKey, "POST", []test.Header{}, body) + r.Header.Set("Content-Type", contentType) + Process(w, r) + return w +} + +func TestMaxExpiryFilesAdd(t *testing.T) { + apiKey := generateNewKey(true, idSuperAdmin, "", "") + apiKey.GrantPermission(models.ApiPermUpload) + database.SaveApiKey(apiKey) + + w := uploadFileWithExpiry(t, apiKey.Id, "0") + test.IsEqualInt(t, w.Code, 200) + test.IsEqualBool(t, getFileInfo(t, w).UnlimitedTime, true) + + setMaxExpiry(t, "3600") + for _, expiryDays := range []string{"0", "30"} { + w = uploadFileWithExpiry(t, apiKey.Id, expiryDays) + test.IsEqualInt(t, w.Code, 400) + test.ResponseBodyIs(t, w, responseExpiryTooLong) + } + w = uploadFileWithExpiry(t, apiKey.Id, "") + test.IsEqualInt(t, w.Code, 200) + file := getFileInfo(t, w) + test.IsEqualBool(t, file.UnlimitedTime, false) + test.IsEqualBool(t, isInSecondsFromNow(file.ExpireAt, 3600), true) +} + +func TestMaxExpiryFilesModify(t *testing.T) { + apiKey := generateNewKey(true, idSuperAdmin, "", "") + apiKey.GrantPermission(models.ApiPermEdit) + database.SaveApiKey(apiKey) + saveTestFile("maxExpiryModify", 0) + + setMaxExpiry(t, "3600") + for _, expiry := range []int64{0, time.Now().Unix() + 7200} { + w, r := getRecorder("/files/modify", apiKey.Id, []test.Header{ + {Name: "id", Value: "maxExpiryModify"}, + {Name: "expiryTimestamp", Value: strconv.FormatInt(expiry, 10)}}) + Process(w, r) + test.IsEqualInt(t, w.Code, 400) + test.ResponseBodyIs(t, w, responseExpiryTooLong) + } + file, ok := database.GetMetaDataById("maxExpiryModify") + test.IsEqualBool(t, ok, true) + test.IsEqualBool(t, file.UnlimitedTime, true) + + expiry := time.Now().Unix() + 1800 + w, r := getRecorder("/files/modify", apiKey.Id, []test.Header{ + {Name: "id", Value: "maxExpiryModify"}, + {Name: "expiryTimestamp", Value: strconv.FormatInt(expiry, 10)}}) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + file, ok = database.GetMetaDataById("maxExpiryModify") + test.IsEqualBool(t, ok, true) + test.IsEqualBool(t, file.UnlimitedTime, false) + test.IsEqualInt64(t, file.ExpireAt, expiry) +} + +func TestMaxExpiryFilesDuplicate(t *testing.T) { + apiKey := generateNewKey(true, idSuperAdmin, "", "") + apiKey.GrantPermission(models.ApiPermUpload) + database.SaveApiKey(apiKey) + saveTestFile("maxExpiryUnlimited", 0) + saveTestFile("maxExpiryShort", time.Now().Unix()+600) + + setMaxExpiry(t, "3600") + w, r := getRecorder("/files/duplicate", apiKey.Id, []test.Header{{Name: "id", Value: "maxExpiryUnlimited"}}) + Process(w, r) + test.IsEqualInt(t, w.Code, 400) + test.ResponseBodyIs(t, w, `{"Result":"error","ErrorMessage":"expiry of the original file: expiry exceeds the server's maximum of 3600 seconds, expiryDays has to be set","ErrorCode":20}`) + + for _, expiryDays := range []string{"0", "30"} { + w, r = getRecorder("/files/duplicate", apiKey.Id, []test.Header{ + {Name: "id", Value: "maxExpiryShort"}, + {Name: "expiryDays", Value: expiryDays}}) + Process(w, r) + test.IsEqualInt(t, w.Code, 400) + test.ResponseBodyIs(t, w, responseExpiryTooLong) + } + + // The original's expiry is within the limit and is kept + w, r = getRecorder("/files/duplicate", apiKey.Id, []test.Header{{Name: "id", Value: "maxExpiryShort"}}) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + var newFile models.FileApiOutput + test.IsNil(t, json.Unmarshal(w.Body.Bytes(), &newFile)) + test.IsEqualBool(t, isInSecondsFromNow(newFile.ExpireAt, 600), true) + + setMaxExpiry(t, "86400") + w, r = getRecorder("/files/duplicate", apiKey.Id, []test.Header{ + {Name: "id", Value: "maxExpiryUnlimited"}, + {Name: "expiryDays", Value: "1"}}) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + test.IsNil(t, json.Unmarshal(w.Body.Bytes(), &newFile)) + test.IsEqualBool(t, newFile.UnlimitedTime, false) + test.IsEqualBool(t, isInSecondsFromNow(newFile.ExpireAt, 86400), true) +} + +func TestMaxExpiryUploadRequestComplete(t *testing.T) { + user, ok := database.GetUser(idSuperAdmin) + test.IsEqualBool(t, ok, true) + fileRequest := filerequest.New(user) + apiKey := generateNewKey(false, idSuperAdmin, "", fileRequest.Id) + fileRequest.ApiKey = apiKey.Id + database.SaveFileRequest(fileRequest) + headers := []test.Header{ + {Name: "uuid", Value: "maxexpiryrequest"}, + {Name: "filename", Value: "maxexpiry.request"}, + {Name: "fileRequestId", Value: fileRequest.Id}, + {Name: "filesize", Value: "13"}} + + createTestChunk(t, "maxexpiryrequest") + w, r := getRecorder("/uploadrequest/chunk/complete", apiKey.Id, headers) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualBool(t, getFileInfo(t, w).UnlimitedTime, true) + + setMaxExpiry(t, "3600") + createTestChunk(t, "maxexpiryrequest") + w, r = getRecorder("/uploadrequest/chunk/complete", apiKey.Id, headers) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + file := getFileInfo(t, w) + test.IsEqualBool(t, file.UnlimitedTime, false) + test.IsEqualBool(t, isInSecondsFromNow(file.ExpireAt, 3600), true) +} + +// saveFileRequest calls /uploadrequest/save and returns the saved file request +func saveFileRequest(t *testing.T, apiKey string, headers []test.Header) (*httptest.ResponseRecorder, models.FileRequest) { + t.Helper() + w, r := getRecorder("/uploadrequest/save", apiKey, headers) + Process(w, r) + var result models.FileRequest + if w.Code == 200 { + test.IsNil(t, json.Unmarshal(w.Body.Bytes(), &result)) + } + return w, result +} + +func TestMaxExpiryURequestSave(t *testing.T) { + apiKey := generateNewKey(true, idSuperAdmin, "", "") + apiKey.GrantPermission(models.ApiPermManageFileRequests) + database.SaveApiKey(apiKey) + + // Without a limit, unlimited requests are allowed and stay the default + w, fileRequest := saveFileRequest(t, apiKey.Id, []test.Header{{Name: "expiry", Value: "0"}}) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualInt64(t, fileRequest.Expiry, 0) + w, fileRequest = saveFileRequest(t, apiKey.Id, []test.Header{}) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualInt64(t, fileRequest.Expiry, 0) + unlimitedId := fileRequest.Id + + setMaxExpiry(t, "3600") + for _, expiry := range []int64{0, time.Now().Unix() + 7200} { + w, _ = saveFileRequest(t, apiKey.Id, []test.Header{{Name: "expiry", Value: strconv.FormatInt(expiry, 10)}}) + test.IsEqualInt(t, w.Code, 400) + test.ResponseBodyIs(t, w, responseExpiryTooLong) + w, _ = saveFileRequest(t, apiKey.Id, []test.Header{ + {Name: "id", Value: unlimitedId}, + {Name: "expiry", Value: strconv.FormatInt(expiry, 10)}}) + test.IsEqualInt(t, w.Code, 400) + test.ResponseBodyIs(t, w, responseExpiryTooLong) + } + expiry := time.Now().Unix() + 1800 + w, fileRequest = saveFileRequest(t, apiKey.Id, []test.Header{{Name: "expiry", Value: strconv.FormatInt(expiry, 10)}}) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualInt64(t, fileRequest.Expiry, expiry) + + // A new request without an expiry gets the default of 14 days, reduced to the limit + w, fileRequest = saveFileRequest(t, apiKey.Id, []test.Header{}) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualBool(t, isInSecondsFromNow(fileRequest.Expiry, 3600), true) + + // Editing a request without an expiry leaves its expiry unchanged + w, fileRequest = saveFileRequest(t, apiKey.Id, []test.Header{ + {Name: "id", Value: unlimitedId}, + {Name: "name", Value: "renamed"}}) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualInt64(t, fileRequest.Expiry, 0) + test.IsEqualString(t, fileRequest.Name, "renamed") + + // A limit longer than the default expiry of 14 days keeps the default + setMaxExpiry(t, "2592000") + w, fileRequest = saveFileRequest(t, apiKey.Id, []test.Header{}) + test.IsEqualInt(t, w.Code, 200) + test.IsEqualBool(t, isInSecondsFromNow(fileRequest.Expiry, 14*24*3600), true) +} + +func TestMaxExpiryConfigInfo(t *testing.T) { + apiKey := generateNewKey(true, idSuperAdmin, "", "") + apiKey.GrantPermission(models.ApiPermUpload) + database.SaveApiKey(apiKey) + result := struct { + MaxExpirySeconds int64 + }{} + + w, r := getRecorder("/info/config", apiKey.Id, []test.Header{}) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + test.IsNil(t, json.Unmarshal(w.Body.Bytes(), &result)) + test.IsEqualInt64(t, result.MaxExpirySeconds, 0) + + setMaxExpiry(t, "3600") + w, r = getRecorder("/info/config", apiKey.Id, []test.Header{}) + Process(w, r) + test.IsEqualInt(t, w.Code, 200) + test.IsNil(t, json.Unmarshal(w.Body.Bytes(), &result)) + test.IsEqualInt64(t, result.MaxExpirySeconds, 3600) +} diff --git a/internal/webserver/api/routing.go b/internal/webserver/api/routing.go index ea7d4687..a21a4958 100644 --- a/internal/webserver/api/routing.go +++ b/internal/webserver/api/routing.go @@ -684,6 +684,7 @@ type paramChunkComplete struct { IsNonBlocking bool `header:"nonblocking"` UnlimitedDownloads bool UnlimitedTime bool + IsExpirySet bool FileHeader chunking.FileHeader foundHeaders map[string]bool } @@ -706,8 +707,9 @@ func (p *paramChunkComplete) ProcessParameter(_ *http.Request) error { } } + p.IsExpirySet = p.foundHeaders["expiryDays"] if p.ExpiryDays == 0 { - if p.foundHeaders["expiryDays"] { + if p.IsExpirySet { p.UnlimitedTime = true } else { p.ExpiryDays = 14 diff --git a/internal/webserver/errorHandling/errorcodes/Errorcodes.go b/internal/webserver/errorHandling/errorcodes/Errorcodes.go index bce8bc56..0339d1b4 100644 --- a/internal/webserver/errorHandling/errorcodes/Errorcodes.go +++ b/internal/webserver/errorHandling/errorcodes/Errorcodes.go @@ -41,4 +41,6 @@ const ( UnsupportedFile // ResourceCanNotBeEdited is returned when a resource cannot be edited ResourceCanNotBeEdited + // ExpiryTooLong is returned when an expiry exceeds the server's maximum (GOKAPI_MAX_EXPIRY_SECONDS) + ExpiryTooLong ) diff --git a/internal/webserver/fileupload/FileUpload.go b/internal/webserver/fileupload/FileUpload.go index bfd80293..6d35a632 100644 --- a/internal/webserver/fileupload/FileUpload.go +++ b/internal/webserver/fileupload/FileUpload.go @@ -2,6 +2,7 @@ package fileupload import ( "errors" + "fmt" "io" "net/http" "strconv" @@ -20,6 +21,12 @@ import ( const minChunkSize = 5 * 1024 * 1024 const minChunkSizeLowMaxChunk = 1 * 1024 * 1024 +// defaultExpiryDays is the expiry of uploads that do not set one +const defaultExpiryDays = 14 + +// ErrorExpiryTooLong is returned when the requested expiry exceeds the server's maximum (GOKAPI_MAX_EXPIRY_SECONDS) +var ErrorExpiryTooLong = errors.New("expiry exceeds the server's maximum") + // ProcessCompleteFile processes a file upload request // This is only used when a complete file is uploaded through the API with /files/add // Normally a file is created from a chunk @@ -146,11 +153,51 @@ func CreateUploadConfig(allowedDownloads, expiryDays int, password string, unlim } } +// CheckMaxExpiry returns an error wrapping ErrorExpiryTooLong if the server limits the lifetime of files +// and the given expiry is unlimited or later than the limit allows +func CheckMaxExpiry(unlimitedTime bool, expiryTimestamp int64) error { + maxSeconds := configuration.GetEnvironment().MaxExpirySeconds + if maxSeconds == 0 { + return nil + } + if unlimitedTime || expiryTimestamp > time.Now().Unix()+maxSeconds { + return fmt.Errorf("%w of %d seconds", ErrorExpiryTooLong, maxSeconds) + } + return nil +} + +// CapToMaxExpiry reduces an expiry that was not chosen by the uploader (the default expiry, or the +// unlimited expiry of file request uploads) to the server's maximum lifetime of files, if one is set +func CapToMaxExpiry(config *models.UploadParameters) { + maxSeconds := configuration.GetEnvironment().MaxExpirySeconds + if maxSeconds == 0 { + return + } + maxTimestamp := time.Now().Unix() + maxSeconds + if config.UnlimitedTime || config.ExpiryTimestamp > maxTimestamp { + config.UnlimitedTime = false + config.ExpiryTimestamp = maxTimestamp + } +} + +// DefaultFileRequestExpiry returns the expiry of a new file request that was saved without one: unlimited (0), +// or, if the server limits the lifetime of files, the default expiry of files reduced to that limit +func DefaultFileRequestExpiry() int64 { + if configuration.GetEnvironment().MaxExpirySeconds == 0 { + return 0 + } + config := CreateUploadConfig(0, defaultExpiryDays, "", false, true, false, 0, "") + CapToMaxExpiry(&config) + return config.ExpiryTimestamp +} + func parseConfig(values formOrHeader) (models.UploadParameters, error) { fileRequestId := values.Get("fileRequestId") if fileRequestId != "" { - return CreateUploadConfig(0, 0, "", - true, true, false, 0, fileRequestId), nil + config := CreateUploadConfig(0, 0, "", + true, true, false, 0, fileRequestId) + CapToMaxExpiry(&config) + return config, nil } allowedDownloads := values.Get("allowedDownloads") expiryDays := values.Get("expiryDays") @@ -159,13 +206,18 @@ func parseConfig(values formOrHeader) (models.UploadParameters, error) { if err != nil { allowedDownloadsInt = 1 } + isExpiryRequested := true expiryDaysInt, err := strconv.Atoi(expiryDays) if err != nil { - expiryDaysInt = 14 + expiryDaysInt = defaultExpiryDays + isExpiryRequested = false } unlimitedDownload := values.Get("isUnlimitedDownload") == "true" unlimitedTime := values.Get("isUnlimitedTime") == "true" + if unlimitedTime { + isExpiryRequested = true + } if allowedDownloadsInt == 0 { unlimitedDownload = true @@ -184,7 +236,16 @@ func parseConfig(values formOrHeader) (models.UploadParameters, error) { return models.UploadParameters{}, err } } - return CreateUploadConfig(allowedDownloadsInt, expiryDaysInt, password, unlimitedTime, unlimitedDownload, isEnd2End, realSize, ""), nil + config := CreateUploadConfig(allowedDownloadsInt, expiryDaysInt, password, unlimitedTime, unlimitedDownload, isEnd2End, realSize, "") + if !isExpiryRequested { + CapToMaxExpiry(&config) + return config, nil + } + err = CheckMaxExpiry(config.UnlimitedTime, config.ExpiryTimestamp) + if err != nil { + return models.UploadParameters{}, err + } + return config, nil } type formOrHeader interface { diff --git a/internal/webserver/fileupload/FileUpload_test.go b/internal/webserver/fileupload/FileUpload_test.go index 52b7e14b..cfc686bc 100644 --- a/internal/webserver/fileupload/FileUpload_test.go +++ b/internal/webserver/fileupload/FileUpload_test.go @@ -3,6 +3,7 @@ package fileupload import ( "bytes" "encoding/json" + "errors" "io" "mime/multipart" "net/http" @@ -12,6 +13,7 @@ import ( "reflect" "strings" "testing" + "time" "github.com/forceu/gokapi/internal/configuration" "github.com/forceu/gokapi/internal/models" @@ -187,6 +189,98 @@ func getFileUploadRecorder(addChunkInfo bool) *http.Request { return r } +// setMaxExpiry sets GOKAPI_MAX_EXPIRY_SECONDS for the duration of the test +func setMaxExpiry(t *testing.T, seconds string) { + t.Helper() + test.IsNil(t, os.Setenv("GOKAPI_MAX_EXPIRY_SECONDS", seconds)) + configuration.Load() + t.Cleanup(func() { + _ = os.Unsetenv("GOKAPI_MAX_EXPIRY_SECONDS") + configuration.Load() + }) +} + +// isInSecondsFromNow returns true if timestamp is now + seconds, allowing for the time the test took +func isInSecondsFromNow(timestamp, seconds int64) bool { + expected := time.Now().Unix() + seconds + return timestamp >= expected-2 && timestamp <= expected +} + +func TestCheckMaxExpiry(t *testing.T) { + now := time.Now().Unix() + test.IsNil(t, CheckMaxExpiry(true, 0)) + test.IsNil(t, CheckMaxExpiry(false, now+10*365*24*3600)) + + setMaxExpiry(t, "3600") + err := CheckMaxExpiry(true, 0) + test.IsEqualBool(t, errors.Is(err, ErrorExpiryTooLong), true) + test.IsEqualString(t, err.Error(), "expiry exceeds the server's maximum of 3600 seconds") + err = CheckMaxExpiry(false, time.Now().Unix()+3601) + test.IsEqualBool(t, errors.Is(err, ErrorExpiryTooLong), true) + test.IsNil(t, CheckMaxExpiry(false, time.Now().Unix()+3600)) + test.IsNil(t, CheckMaxExpiry(false, time.Now().Unix()+60)) +} + +func TestCapToMaxExpiry(t *testing.T) { + config := CreateUploadConfig(1, 0, "", true, false, false, 0, "") + CapToMaxExpiry(&config) + test.IsEqualBool(t, config.UnlimitedTime, true) + + setMaxExpiry(t, "3600") + CapToMaxExpiry(&config) + test.IsEqualBool(t, config.UnlimitedTime, false) + test.IsEqualBool(t, isInSecondsFromNow(config.ExpiryTimestamp, 3600), true) + + config = CreateUploadConfig(1, 14, "", false, false, false, 0, "") + CapToMaxExpiry(&config) + test.IsEqualBool(t, isInSecondsFromNow(config.ExpiryTimestamp, 3600), true) + + config.ExpiryTimestamp = time.Now().Unix() + 60 + CapToMaxExpiry(&config) + test.IsEqualBool(t, isInSecondsFromNow(config.ExpiryTimestamp, 60), true) + + // A limit longer than the default expiry keeps the default + setMaxExpiry(t, "2592000") + config = CreateUploadConfig(1, 14, "", false, false, false, 0, "") + CapToMaxExpiry(&config) + test.IsEqualBool(t, config.UnlimitedTime, false) + test.IsEqualBool(t, isInSecondsFromNow(config.ExpiryTimestamp, 14*24*3600), true) +} + +func TestParseConfigMaxExpiry(t *testing.T) { + config, err := parseConfig(url.Values{"fileRequestId": {"request"}}) + test.IsNil(t, err) + test.IsEqualBool(t, config.UnlimitedTime, true) + config, err = parseConfig(url.Values{"expiryDays": {"0"}}) + test.IsNil(t, err) + test.IsEqualBool(t, config.UnlimitedTime, true) + + setMaxExpiry(t, "3600") + for _, values := range []url.Values{ + {"expiryDays": {"1"}}, + {"expiryDays": {"0"}}, + {"isUnlimitedTime": {"true"}}, + } { + _, err = parseConfig(values) + test.IsEqualBool(t, errors.Is(err, ErrorExpiryTooLong), true) + } + for _, values := range []url.Values{ + {}, + {"expiryDays": {"invalid"}}, + {"fileRequestId": {"request"}}, + } { + config, err = parseConfig(values) + test.IsNil(t, err) + test.IsEqualBool(t, config.UnlimitedTime, false) + test.IsEqualBool(t, isInSecondsFromNow(config.ExpiryTimestamp, 3600), true) + } + + setMaxExpiry(t, "86400") + config, err = parseConfig(url.Values{"expiryDays": {"1"}}) + test.IsNil(t, err) + test.IsEqualBool(t, isInSecondsFromNow(config.ExpiryTimestamp, 86400), true) +} + type testData struct { allowedDownloads, expiryDays, password, isE2E, realSize string } diff --git a/internal/webserver/web/static/apidocumentation/openapi.json b/internal/webserver/web/static/apidocumentation/openapi.json index 49f69889..f705f60f 100644 --- a/internal/webserver/web/static/apidocumentation/openapi.json +++ b/internal/webserver/web/static/apidocumentation/openapi.json @@ -496,7 +496,7 @@ { "name": "expiryDays", "in": "header", - "description": "How many days the file will be stored. Default of 14 will be used if empty. Unlimited if 0 is passed.", + "description": "How many days the file will be stored. Default of 14 will be used if empty. Unlimited if 0 is passed. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), values above it and unlimited are refused and the default is reduced to the maximum.", "required": false, "schema": { "type": "integer" @@ -1026,7 +1026,7 @@ "name": "expiryDays", "in": "header", "required": false, - "description": "How many days the file will be stored. Original value from web interface will be used if empty. Unlimited if 0 is passed.", + "description": "How many days the file will be stored. Original value from web interface will be used if empty. Unlimited if 0 is passed. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), values above it and unlimited are refused, and an empty value is refused if the original value exceeds the maximum.", "schema": { "type": "integer" } @@ -1181,7 +1181,7 @@ "schema": { "type": "integer" }, - "description": "Unix timestamp of the file expiration date. Unlimited if 0 is passed." + "description": "Unix timestamp of the file expiration date. Unlimited if 0 is passed. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), values above it and unlimited are refused." }, { "name": "password", @@ -1756,7 +1756,7 @@ { "name": "expiry", "in": "header", - "description": "The expiry as a UTC unix timestamp. No expiry if 0", + "description": "The expiry as a UTC unix timestamp. No expiry if 0. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), unlimited and values above it are refused, and a new request without an expiry expires after 14 days or the maximum, whichever is shorter.", "required": false, "style": "simple", "explode": false, @@ -2590,6 +2590,11 @@ "MaxChunksize": { "type": "integer", "example": 40 + }, + "MaxExpirySeconds": { + "type": "integer", + "description": "The maximum time in seconds that a file can be stored before it expires (GOKAPI_MAX_EXPIRY_SECONDS). 0 if there is no limit", + "example": 0 } }, "description": "ConfigInfo is the struct used for returning configuration data" @@ -2627,7 +2632,7 @@ }, "expiryDays": { "type": "integer", - "description": "How many days the file will be stored. Default of 14 will be used if empty. Unlimited if 0 is passed." + "description": "How many days the file will be stored. Default of 14 will be used if empty. Unlimited if 0 is passed. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), values above it and unlimited are refused and the default is reduced to the maximum." }, "password": { "type": "string", diff --git a/internal/webserver/web/static/js/admin_ui_allPages.js b/internal/webserver/web/static/js/admin_ui_allPages.js index d0a66dcd..cdab8383 100644 --- a/internal/webserver/web/static/js/admin_ui_allPages.js +++ b/internal/webserver/web/static/js/admin_ui_allPages.js @@ -30,10 +30,11 @@ function hideToast() { var calendarInstance = null; -function createCalendar(element, timestamp) { +// maxTimestamp is optional, no later date can be selected if it is set +function createCalendar(element, timestamp, maxTimestamp) { const expiryDate = new Date(timestamp * 1000); - calendarInstance = flatpickr(document.getElementById(element), { + let options = { enableTime: true, dateFormat: 'U', // Unix timestamp altInput: true, @@ -42,7 +43,11 @@ function createCalendar(element, timestamp) { time_24hr: true, defaultDate: expiryDate, minDate: 'today', - }); + }; + if (maxTimestamp) { + options.maxDate = new Date(maxTimestamp * 1000); + } + calendarInstance = flatpickr(document.getElementById(element), options); } diff --git a/internal/webserver/web/static/js/admin_ui_filerequest.js b/internal/webserver/web/static/js/admin_ui_filerequest.js index 00ca5167..bf082b79 100644 --- a/internal/webserver/web/static/js/admin_ui_filerequest.js +++ b/internal/webserver/web/static/js/admin_ui_filerequest.js @@ -254,17 +254,34 @@ function setModalValues(id, name, maxFiles, maxSize, expiry, notes) { document.getElementById("mc_maxsize").checked = true; } + const defaultDate = Math.floor(new Date(Date.now() + (14 * 24 * 60 * 60 * 1000)).getTime() / 1000); + let maxExpiryTimestamp = 0; + let checkboxExpiry = document.getElementById("mc_expiry"); + if (maxExpirySeconds > 0) { + // The server limits the lifetime of files: requests cannot accept uploads without a time limit + maxExpiryTimestamp = Math.floor(Date.now() / 1000) + maxExpirySeconds; + if (expiry === null || expiry == 0) { + expiry = Math.min(defaultDate, maxExpiryTimestamp); + } else if (expiry > maxExpiryTimestamp) { + expiry = maxExpiryTimestamp; + } + checkboxExpiry.disabled = true; + checkboxExpiry.title = "The server limits the lifetime of files"; + } else { + checkboxExpiry.disabled = false; + checkboxExpiry.title = "Expiry"; + } + if (expiry === null || expiry == 0) { - const defaultDate = Math.floor(new Date(Date.now() + (14 * 24 * 60 * 60 * 1000)).getTime() / 1000); document.getElementById("mi_expiry").disabled = true; - document.getElementById("mc_expiry").checked = false; + checkboxExpiry.checked = false; document.getElementById("mi_expiry").value = defaultDate; createCalendar("mi_expiry", defaultDate); } else { document.getElementById("mi_expiry").value = expiry; document.getElementById("mi_expiry").disabled = false; - document.getElementById("mc_expiry").checked = true; - createCalendar("mi_expiry", expiry); + checkboxExpiry.checked = true; + createCalendar("mi_expiry", expiry, maxExpiryTimestamp); } document.getElementById("mNotes").value = notes; } diff --git a/internal/webserver/web/static/js/admin_ui_upload.js b/internal/webserver/web/static/js/admin_ui_upload.js index 890a2762..6482e17b 100644 --- a/internal/webserver/web/static/js/admin_ui_upload.js +++ b/internal/webserver/web/static/js/admin_ui_upload.js @@ -24,6 +24,7 @@ function initDropzone() { dropzoneObject = this; this.on("addedfile", file => { file.upload.uuid = getUuid(); + clampExpiryDaysToMax(); saveUploadDefaults(); addFileProgress(file); }); @@ -163,7 +164,49 @@ function setUploadDefaults() { if (defaultUnlimitedTime) { document.getElementById("expiryDays").disabled = true; } + if (maxExpirySeconds > 0) { + applyMaxExpiryToUpload(); + } +} +// The server limits the expiry (GOKAPI_MAX_EXPIRY_SECONDS): files cannot be stored without a time limit +// and the expiry in days cannot be longer than the maximum +function applyMaxExpiryToUpload() { + const enableTimeLimit = document.getElementById("enableTimeLimit"); + const expiryDays = document.getElementById("expiryDays"); + const maxDays = Math.floor(maxExpirySeconds / 86400); + + enableTimeLimit.checked = true; + enableTimeLimit.disabled = true; + if (maxDays < 1) { + // The maximum cannot be entered in days. An empty value is not sent, + // so the server applies its default, which is the maximum + expiryDays.value = ""; + expiryDays.disabled = true; + return; + } + expiryDays.disabled = false; + expiryDays.max = maxDays; + if (expiryDays.value === "" || Number(expiryDays.value) > maxDays) { + expiryDays.value = maxDays; + } + expiryDays.addEventListener("input", clampExpiryDaysToMax); + expiryDays.addEventListener("change", clampExpiryDaysToMax); +} + +// The max attribute only limits the arrows, a typed value can still be larger. The server +// would only refuse it after all chunks have been uploaded +function clampExpiryDaysToMax() { + const maxDays = Math.floor(maxExpirySeconds / 86400); + const expiryDays = document.getElementById("expiryDays"); + if (maxDays < 1 || expiryDays.value === "") { + return; + } + if (Number(expiryDays.value) > maxDays) { + expiryDays.value = maxDays; + } else if (Number(expiryDays.value) < 1) { + expiryDays.value = 1; + } } function saveUploadDefaults() { @@ -204,6 +247,7 @@ function sendChunkComplete(file, done) { let realsize = file.size; let contenttype = file.type; let allowedDownloads = document.getElementById("allowedDownloads").value; + clampExpiryDaysToMax(); let expiryDays = document.getElementById("expiryDays").value; let password = document.getElementById("password").value; let isE2E = file.isEndToEndEncrypted === true; @@ -406,10 +450,21 @@ function showEditModal(filename, id, downloads, expiry, password, unlimitedown, $('body').append(myClone); }); + let maxExpiryTimestamp = 0; + if (maxExpirySeconds > 0) { + // The server limits the expiry: files cannot be stored without a time limit + maxExpiryTimestamp = Math.floor(Date.now() / 1000) + maxExpirySeconds; + if (unlimitedtime || expiry > maxExpiryTimestamp) { + expiry = maxExpiryTimestamp; + } + unlimitedtime = false; + document.getElementById("mc_expiry").parentElement.classList.add("d-none"); + } + document.getElementById("m_filenamelabel").innerText = filename; document.getElementById("mc_expiry").setAttribute("data-timestamp", expiry); document.getElementById("mb_save").setAttribute('data-fileid', id); - createCalendar("mi_edit_expiry", expiry); + createCalendar("mi_edit_expiry", expiry, maxExpiryTimestamp); if (unlimitedown) { document.getElementById("mi_edit_down").value = "1"; diff --git a/internal/webserver/web/static/js/min/admin.min.ccb62a8d5b.js b/internal/webserver/web/static/js/min/admin.min.ccb62a8d5b.js index 81cd0526..344ee48b 100644 --- a/internal/webserver/web/static/js/min/admin.min.ccb62a8d5b.js +++ b/internal/webserver/web/static/js/min/admin.min.ccb62a8d5b.js @@ -1,6 +1,6 @@ -const storedTokens=new Map;async function getToken(e,t){const n="./auth/token";if(!t){if(!storedTokens.has(e))return getToken(e,!0);let t=storedTokens.get(e);return t.expiry-Date.now()/1e3<60?getToken(e,!0):t.key}const s={method:"POST",headers:{"Content-Type":"application/json",permission:e}};try{const o=await fetch(n,s);if(!o.ok)throw new Error(`Request failed with status: ${o.status}`);const t=await o.json();if(!t.hasOwnProperty("key"))throw new Error(`Invalid response when trying to get token`);return storedTokens.set(e,{key:t.key,expiry:t.expiry}),t.key}catch(e){throw console.error("Error in getToken:",e),e}}async function apiAuthModify(e,t,n){const o="./api/auth/modify",i="PERM_API_MOD";let s;try{s=await getToken(i,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const a={method:"POST",headers:{"Content-Type":"application/json",apikey:s,targetKey:e,permission:t,permissionModifier:n}};try{const e=await fetch(o,a);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiAuthModify:",e),e}}async function apiAuthFriendlyName(e,t){const s="./api/auth/friendlyname",o="PERM_API_MOD";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"PUT",headers:{"Content-Type":"application/json",apikey:n,targetKey:e,friendlyName:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiAuthModify:",e),e}}async function apiAuthDelete(e){const n="./api/auth/delete",s="PERM_API_MOD";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t,targetKey:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiAuthDelete:",e),e}}async function apiAuthCreate(){const t="./api/auth/create",n="PERM_API_MOD";let e;try{e=await getToken(n,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const s={method:"POST",headers:{"Content-Type":"application/json",apikey:e,basicPermissions:"true"}};try{const e=await fetch(t,s);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const n=await e.json();return n}catch(e){throw console.error("Error in apiAuthCreate:",e),e}}async function apiChunkComplete(e,t,n,s,o,i,a,r,c,l){const u="./api/chunk/complete",h="PERM_UPLOAD";let d;try{d=await getToken(h,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const m={method:"POST",headers:{"Content-Type":"application/json",apikey:d,uuid:e,filename:"base64:"+Base64.encode(t),filesize:n,realsize:s,contenttype:o,allowedDownloads:i,expiryDays:a,password:r,isE2E:c,nonblocking:l}};try{const e=await fetch(u,m);if(!e.ok){let t;try{const n=await e.json();t=n.ErrorMessage||`Request failed with status: ${e.status}`}catch{const n=await e.text();t=n||`Request failed with status: ${e.status}`}throw new Error(t)}const t=await e.json();return t}catch(e){throw console.error("Error in apiChunkComplete:",e),e}}async function apiFilesReplace(e,t){const s="./api/files/replace",o="PERM_REPLACE";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"PUT",headers:{"Content-Type":"application/json",id:e,apikey:n,idNewContent:t,deleteNewFile:!1}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesReplace:",e),e}}async function apiFilesListById(e){const n="./api/files/list/"+e,s="PERM_VIEW";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"GET",headers:{"Content-Type":"application/json",apikey:t}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesListById:",e),e}}async function apiFilesListDownloadSingle(e){const n="./api/files/download/"+e,s="PERM_DOWNLOAD";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"GET",headers:{"Content-Type":"application/json",apikey:t,presignUrl:!0}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesListDownloadSingle:",e),e}}async function apiFilesListDownloadZip(e,t,n){const o="./api/files/downloadzip",i="PERM_DOWNLOAD";let s;try{s=await getToken(i,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const a={method:"GET",headers:{"Content-Type":"application/json",apikey:s,ids:e,filename:"base64:"+Base64.encode(n),isFileRequestId:t,presignUrl:!0}};try{const e=await fetch(o,a);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesListDownloadZip:",e),e}}async function apiFilesModify(e,t,n,s,o){const a="./api/files/modify",r="PERM_EDIT";let i;try{i=await getToken(r,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const c={method:"PUT",headers:{"Content-Type":"application/json",id:e,apikey:i,allowedDownloads:t,expiryTimestamp:n,password:s,originalPassword:o}};try{const e=await fetch(a,c);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesModify:",e),e}}async function apiFilesDelete(e,t){const s="./api/files/delete",o="PERM_DELETE";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"POST",headers:{"Content-Type":"application/json",apikey:n,id:e,delay:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiFilesDelete:",e),e}}async function apiFilesRestore(e){const n="./api/files/restore",s="PERM_DELETE";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t,id:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesRestore:",e),e}}async function apiUserCreate(e){const n="./api/user/create",s="PERM_MANAGE_USERS";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t,username:e}};try{const e=await fetch(n,o);if(!e.ok)throw e.status==409?new Error("duplicate"):new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiUserModify:",e),e}}async function apiUserModify(e,t,n){const o="./api/user/modify",i="PERM_MANAGE_USERS";let s;try{s=await getToken(i,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const a={method:"POST",headers:{"Content-Type":"application/json",apikey:s,userid:e,userpermission:t,permissionModifier:n}};try{const e=await fetch(o,a);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiUserModify:",e),e}}async function apiUserChangeRank(e,t){const s="./api/user/changeRank",o="PERM_MANAGE_USERS";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"POST",headers:{"Content-Type":"application/json",apikey:n,userid:e,newRank:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiUserModify:",e),e}}async function apiUserDelete(e,t){const s="./api/user/delete",o="PERM_MANAGE_USERS";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"POST",headers:{"Content-Type":"application/json",apikey:n,userid:e,deleteFiles:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiUserDelete:",e),e}}async function apiUserResetPassword(e,t){const s="./api/user/resetPassword",o="PERM_MANAGE_USERS";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"POST",headers:{"Content-Type":"application/json",apikey:n,userid:e,generateNewPassword:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiUserResetPassword:",e),e}}async function apiLogSystemStatus(){const t="./api/logs/systemStatus",n="PERM_MANAGE_LOGS";let e;try{e=await getToken(n,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const s={method:"GET",headers:{"Content-Type":"application/json",apikey:e}};try{const e=await fetch(t,s);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const n=await e.json();return n}catch(e){throw console.error("Error in apiLogSystemStatus:",e),e}}async function apiLogResetTraffic(){const t="./api/logs/resetTraffic",n="PERM_MANAGE_LOGS";let e;try{e=await getToken(n,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const s={method:"GET",headers:{"Content-Type":"application/json",apikey:e}};try{const e=await fetch(t,s);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiLogResetTraffic:",e),e}}async function apiLogGet(e){const n="./api/logs/get",s="PERM_MANAGE_LOGS";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"GET",headers:{"Content-Type":"application/json",apikey:t,timestamp:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiLogGet:",e),e}}async function apiLogsDelete(e){const n="./api/logs/delete",s="PERM_MANAGE_LOGS";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t,timestamp:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiLogsDelete:",e),e}}async function apiE2eGet(){const t="./api/e2e/get",n="PERM_UPLOAD";let e;try{e=await getToken(n,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const s={method:"POST",headers:{"Content-Type":"application/json",apikey:e}};try{const e=await fetch(t,s);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);return await e.text()}catch(e){throw console.error("Error in apiE2eGet:",e),e}}async function apiE2eMutexLockUnlock(e){let t="./api/e2e/mutex/lock";e&&(t="./api/e2e/mutex/unlock");const s="PERM_UPLOAD";let n;try{n=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"GET",headers:{"Content-Type":"application/json",apikey:n}};try{const e=await fetch(t,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);return await e.text()}catch(e){throw console.error("Error in apiE2eMutexLock:",e),e}}async function apiE2eStore(e){const n="./api/e2e/set",s="PERM_UPLOAD";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t},body:JSON.stringify({content:e})};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiE2eStore:",e),e}}async function apiURequestDelete(e){const n="./api/uploadrequest/delete",s="PERM_MANAGE_FILE_REQUESTS,PERM_DELETE";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"DELETE",headers:{"Content-Type":"application/json",apikey:t,id:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiURequestDelete:",e),e}}async function apiURequestSave(e,t,n,s,o,i){const r="./api/uploadrequest/save",c="PERM_MANAGE_FILE_REQUESTS";let a;try{a=await getToken(c,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const l={method:"POST",headers:{"Content-Type":"application/json",apikey:a,id:e,name:"base64:"+Base64.encode(t),expiry:o,maxfiles:n,maxsize:s,notes:"base64:"+Base64.encode(i)}};try{const e=await fetch(r,l);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiURequestDelete:",e),e}}try{var toastId,calendarInstance,dropzoneObject,isE2EEnabled,isUploading,rowCount,sseWorkerPort,statusItemCount,clipboard=new ClipboardJS(".copyurl")}catch{}function showToast(e,t){let n=document.getElementById("toastnotification");typeof t!="undefined"?n.innerText=t:n.innerText=n.dataset.default,n.classList.add("show"),clearTimeout(toastId),toastId=setTimeout(()=>{hideToast()},e)}function hideToast(){document.getElementById("toastnotification").classList.remove("show")}calendarInstance=null;function createCalendar(e,t){const n=new Date(t*1e3);calendarInstance=flatpickr(document.getElementById(e),{enableTime:!0,dateFormat:"U",altInput:!0,altFormat:"Y-m-d H:i",allowInput:!0,time_24hr:!0,defaultDate:n,minDate:"today"})}function handleEditCheckboxChange(e){var t=document.getElementById(e.getAttribute("data-toggle-target")),n=e.getAttribute("data-timestamp");e.checked?(t.classList.remove("disabled"),t.removeAttribute("disabled"),n!=null&&(calendarInstance._input.disabled=!1)):(n!=null&&(calendarInstance._input.disabled=!0),t.classList.add("disabled"),t.setAttribute("disabled",!0))}function downloadFileWithPresign(e){apiFilesListDownloadSingle(e).then(e=>{if(!e.hasOwnProperty("downloadUrl"))throw new Error("Unable to get presigned key");const t=document.createElement("a");t.href=e.downloadUrl,t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}).catch(e=>{alert("Unable to download: "+e),console.error("Error:",e)})}function downloadFilesZipWithPresign(e,t,n){apiFilesListDownloadZip(e,t,n).then(e=>{if(!e.hasOwnProperty("downloadUrl"))throw new Error("Unable to get presigned key");const t=document.createElement("a");t.href=e.downloadUrl,t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}).catch(e=>{alert("Unable to download: "+e),console.error("Error:",e)})}function doLogout(){typeof sseWorkerPort!="undefined"&&sseWorkerPort!==null&&sseWorkerPort.postMessage({type:"shutdown"}),window.location.href="./logout"}function changeApiPermission(e,t,n){var o,i,s=document.getElementById(n);if(s.classList.contains("perm-processing")||s.classList.contains("perm-nochange"))return;o=s.classList.contains("perm-granted"),s.classList.add("perm-processing"),s.classList.remove("perm-granted"),s.classList.remove("perm-notgranted"),i="GRANT",o&&(i="REVOKE"),apiAuthModify(e,t,i).then(e=>{o?(s.classList.add("perm-notgranted"),s.classList.add("perm-nownotgranted")):(s.classList.add("perm-granted"),s.classList.add("perm-nowgranted")),s.classList.remove("perm-processing"),setTimeout(()=>{s.classList.remove("perm-nowgranted"),s.classList.remove("perm-nownotgranted")},1e3)}).catch(e=>{o?s.classList.add("perm-granted"):s.classList.add("perm-notgranted"),s.classList.remove("perm-processing"),alert("Unable to set permission: "+e),console.error("Error:",e)})}function deleteApiKey(e){document.getElementById("delete-"+e).disabled=!0,apiAuthDelete(e).then(t=>{document.getElementById("row-"+e).classList.add("rowDeleting"),setTimeout(()=>{document.getElementById("row-"+e).remove()},290)}).catch(e=>{alert("Unable to delete API key: "+e),console.error("Error:",e)})}function newApiKey(){document.getElementById("button-newapi").disabled=!0,apiAuthCreate().then(e=>{addRowApi(e.Id,e.PublicId),document.getElementById("button-newapi").disabled=!1}).catch(e=>{alert("Unable to create API key: "+e),console.error("Error:",e)})}function addFriendlyNameChange(e){let t=document.getElementById("friendlyname-"+e);if(t.classList.contains("isBeingEdited"))return;t.classList.add("isBeingEdited");let i=t.innerText,n=document.createElement("input");n.size=5,n.value=i;let s=!0,o=function(){if(!s)return;s=!1;let o=n.value;o==""&&(o="Unnamed key"),t.innerText=o,t.classList.remove("isBeingEdited"),apiAuthFriendlyName(e,o).catch(e=>{alert("Unable to save name: "+e),console.error("Error:",e)})};n.onblur=o,n.addEventListener("keyup",function(e){e.keyCode===13&&(e.preventDefault(),o())}),t.innerText="",t.appendChild(n),n.focus()}function addRowApi(e,t){let p=document.getElementById("apitable"),s=p.insertRow(0);s.id="row-"+t;let i=0,c=s.insertCell(i++),l=s.insertCell(i++),d=s.insertCell(i++),a=s.insertCell(i++),u;canViewOtherApiKeys&&(u=s.insertCell(i++));let h=s.insertCell(i++);canViewOtherApiKeys&&(u.classList.add("newApiKey"),u.innerText=userName),c.classList.add("newApiKey"),l.classList.add("newApiKey"),d.classList.add("newApiKey"),a.classList.add("newApiKey"),a.classList.add("prevent-select"),h.classList.add("newApiKey"),c.innerText="Unnamed key",c.id="friendlyname-"+t,c.onclick=function(){addFriendlyNameChange(t)},l.innerText=e,l.classList.add("font-monospace"),d.innerText="Never";const r=document.createElement("div");r.className="btn-group",r.setAttribute("role","group");const n=document.createElement("button");n.type="button",n.dataset.clipboardText=e,n.title="Copy API Key",n.className="copyurl btn btn-outline-light btn-sm",n.setAttribute("onclick","showToast(1000)");const m=document.createElement("i");m.className="bi bi-copy",n.appendChild(m);const o=document.createElement("button");o.type="button",o.id=`delete-${t}`,o.title="Delete",o.className="btn btn-outline-danger btn-sm",o.setAttribute("onclick",`deleteApiKey('${t}')`);const f=document.createElement("i");f.className="bi bi-trash3",o.appendChild(f),r.appendChild(n),r.appendChild(o),h.appendChild(r);const g=[{perm:"PERM_VIEW",icon:"bi-eye",granted:!0,title:"List Uploads"},{perm:"PERM_UPLOAD",icon:"bi-file-earmark-plus",granted:!0,title:"Upload"},{perm:"PERM_EDIT",icon:"bi-pencil",granted:!0,title:"Edit Uploads"},{perm:"PERM_DELETE",icon:"bi-trash3",granted:!0,title:"Delete Uploads"},{perm:"PERM_REPLACE",icon:"bi-recycle",granted:!1,title:"Replace Uploads"},{perm:"PERM_DOWNLOAD",icon:"bi-box-arrow-in-down",granted:!1,title:"Download Files"},{perm:"PERM_MANAGE_FILE_REQUESTS",icon:"bi-file-earmark-arrow-up",granted:!1,title:"Manage File Requests"},{perm:"PERM_MANAGE_USERS",icon:"bi-people",granted:!1,title:"Manage Users"},{perm:"PERM_MANAGE_LOGS",icon:"bi-card-list",granted:!1,title:"Manage System Logs"},{perm:"PERM_API_MOD",icon:"bi-sliders2",granted:!1,title:"Manage API Keys"}];if(g.forEach(({perm:e,icon:n,granted:s,title:o})=>{const i=document.createElement("i"),r=`${e.toLowerCase()}_${t}`;i.id=r,i.className=`bi ${n} ${s?"perm-granted":"perm-notgranted"}`,i.title=o,i.setAttribute("onclick",`changeApiPermission("${t}","${e}", "${r}");`),a.appendChild(i),a.appendChild(document.createTextNode(" "))}),!canReplaceFiles){let e=document.getElementById("perm_replace_"+t);e.classList.add("perm-unavailable"),e.classList.add("perm-nochange")}if(!canManageUsers){let e=document.getElementById("perm_manage_users_"+t);e.classList.add("perm-unavailable"),e.classList.add("perm-nochange")}if(!canViewSystemLog){let e=document.getElementById("perm_manage_logs_"+t);e.classList.add("perm-unavailable"),e.classList.add("perm-nochange")}if(!canCreateFileRequest){let e=document.getElementById("perm_manage_file_requests_"+t);e.classList.add("perm-unavailable"),e.classList.add("perm-nochange")}setTimeout(()=>{c.classList.remove("newApiKey"),l.classList.remove("newApiKey"),d.classList.remove("newApiKey"),a.classList.remove("newApiKey"),h.classList.remove("newApiKey")},700)}function deleteFileRequest(e){document.getElementById("delete-"+e).disabled=!0,apiURequestDelete(e).then(t=>{const s=document.getElementById("row-"+e),n=document.getElementById("filelist-"+e);s.classList.add("rowDeleting"),n!==null&&n.classList.add("rowDeleting"),setTimeout(()=>{s.remove(),n!==null&&n.remove()},290)}).catch(e=>{alert("Unable to delete file request: "+e),console.error("Error:",e)})}function deleteOrShowModal(e,t){const n=getFileRequestUploadCount(e);n===0?deleteFileRequest(e):showDeleteFRequestModal(e,t,n)}function deleteFileFr(e,t){document.getElementById("button-delete-"+e).disabled=!0;let n=document.getElementById("cell-listupload-"+e);apiFilesDelete(e,10).then(s=>{changeFileCountFr(t,-1),n.classList.add("rowDeleting"),setTimeout(()=>{n.remove()},290),updateDownloadButton(t),showToastFileDeletionFr(e)}).catch(e=>{alert("Unable to delete file: "+e),console.error("Error:",e)})}function changeFileCountFr(e,t){let n=document.getElementById("totalFiles-fr-"+e),s=getFileRequestUploadCount(e)+t;n.innerText=s}function getFileRequestUploadCount(e){let t=document.getElementById("totalFiles-fr-"+e);return Number(t.innerText)||0}function updateDownloadButton(e){const t=document.getElementById(`download-${e}`);if(!t)return;const n=document.getElementById("totalFiles-fr-"+e),o=n?n.innerText.split("+")[0].trim():"",s=Number(o)||0,i=t.getAttribute("onclick")||"";if(s===0){t.classList.add("disabled"),t.removeAttribute("onclick");return}if(s===1){let n=getFileIdsForFilerequest(e)[0];t.setAttribute("onclick",`downloadFileWithPresign('${n}');`)}}function getFileIdsForFilerequest(e){const t=document.querySelectorAll(`#collapse-filelist-${e} .filelist-item:not(.rowDeleting)`);return Array.from(t).map(e=>e.id.replace("cell-listupload-","")).filter(e=>e)}function showToastFileDeletionFr(e){let t=document.getElementById("toastnotificationUndo"),n=document.getElementById("cell-name-"+e).innerText,s=document.getElementById("toastFilename"),o=document.getElementById("toastUndoButton");s.innerText=n,o.dataset.fileid=e,hideToast(),t.classList.add("show"),clearTimeout(toastId),toastId=setTimeout(()=>{hideFileToast()},5e3)}function handleUndoFr(e){hideFileToast(),apiFilesRestore(e.dataset.fileid).then(e=>{window.location.reload()}).catch(e=>{alert("Unable to restore file: "+e),console.error("Error:",e)})}function showDeleteFRequestModal(e,t,n){document.getElementById("deleteModalBodyName").innerText=t,document.getElementById("deleteModalBodyCount").innerText=n,$("#deleteModal").modal("show"),document.getElementById("buttonDelete").onclick=function(){$("#deleteModal").modal("hide"),deleteFileRequest(e)}}function newFileRequest(){loadFileRequestDefaults(),document.getElementById("m_urequestlabel").innerText="New File Request",$("#addEditModal").modal("show"),document.getElementById("b_fr_save").onclick=function(){saveFileRequestDefaults(),saveFileRequest(),$("#addEditModal").modal("hide")}}function saveFileRequestDefaults(){if(document.getElementById("mc_maxfiles").checked?localStorage.setItem("fr_maxfiles",document.getElementById("mi_maxfiles").value):localStorage.setItem("fr_maxfiles",0),document.getElementById("mc_maxsize").checked?localStorage.setItem("fr_maxsize",document.getElementById("mi_maxsize").value):localStorage.setItem("fr_maxsize",0),document.getElementById("mc_expiry").checked){let e=document.getElementById("mi_expiry").value-Math.round(Date.now()/1e3);localStorage.setItem("fr_expiry",e)}else localStorage.setItem("fr_expiry",0)}function loadFileRequestDefaults(){const t=localStorage.getItem("fr_maxfiles"),n=localStorage.getItem("fr_maxsize");let e=localStorage.getItem("fr_expiry");if(e!=="0"&&e!==null){let t=new Date(Date.now()+Number(e*1e3));t.setHours(12,0,0,0),e=Math.floor(t.getTime()/1e3)}setModalValues("","",t,n,e,"")}function setModalValues(e,t,n,s,o,i){if(document.getElementById("freqId").value=e,t===null?document.getElementById("mFriendlyName").value="":document.getElementById("mFriendlyName").value=t,limitMaxFiles!=0){let e=document.getElementById("mc_maxfiles");(n===null||n==0)&&(n=limitMaxFiles),e.checked=!0,e.disabled=!0,e.title="Only admins can set this to unlimited",e.value="1",document.getElementById("mi_maxfiles").setAttribute("max",limitMaxFiles)}else{let e=document.getElementById("mc_maxfiles");e.disabled=!1,e.title="",document.getElementById("mi_maxfiles").setAttribute("max","")}if(limitMaxSize!=0){let e=document.getElementById("mc_maxsize");(s===null||s==0)&&(s=limitMaxSize),e.checked=!0,e.disabled=!0,e.title="Only admins can set this to unlimited",e.value="1",document.getElementById("mi_maxsize").setAttribute("max",limitMaxSize)}else{let e=document.getElementById("mc_maxsize");e.disabled=!1,e.title="",document.getElementById("mi_maxsize").setAttribute("max","")}if(n===null||n==0?(document.getElementById("mi_maxfiles").value="1",document.getElementById("mi_maxfiles").disabled=!0,document.getElementById("mc_maxfiles").checked=!1):(document.getElementById("mi_maxfiles").value=n,document.getElementById("mi_maxfiles").disabled=!1,document.getElementById("mc_maxfiles").checked=!0),s===null||s==0?(document.getElementById("mi_maxsize").value="10",document.getElementById("mi_maxsize").disabled=!0,document.getElementById("mc_maxsize").checked=!1):(document.getElementById("mi_maxsize").value=s,document.getElementById("mi_maxsize").disabled=!1,document.getElementById("mc_maxsize").checked=!0),o===null||o==0){const e=Math.floor(new Date(Date.now()+14*24*60*60*1e3).getTime()/1e3);document.getElementById("mi_expiry").disabled=!0,document.getElementById("mc_expiry").checked=!1,document.getElementById("mi_expiry").value=e,createCalendar("mi_expiry",e)}else document.getElementById("mi_expiry").value=o,document.getElementById("mi_expiry").disabled=!1,document.getElementById("mc_expiry").checked=!0,createCalendar("mi_expiry",o);document.getElementById("mNotes").value=i}function editFileRequest(e,t,n,s,o,i){setModalValues(e,t,n,s,o,i),document.getElementById("m_urequestlabel").innerText="Edit File Request",$("#addEditModal").modal("show"),document.getElementById("b_fr_save").onclick=function(){saveFileRequest(),$("#addEditModal").modal("hide")}}function saveFileRequest(){const s=document.getElementById("b_fr_save"),o=document.getElementById("freqId").value,i=document.getElementById("mFriendlyName").value,a=document.getElementById("mNotes").value;let e=0,t=0,n=0;document.getElementById("mc_maxfiles").checked&&(e=document.getElementById("mi_maxfiles").value),document.getElementById("mc_maxsize").checked&&(t=document.getElementById("mi_maxsize").value),document.getElementById("mc_expiry").checked&&(n=document.getElementById("mi_expiry").value),s.disabled=!0,apiURequestSave(o,i,e,t,n,a).then(e=>{document.getElementById("b_fr_save").disabled=!1,insertOrReplaceFileRequest(e)}).catch(e=>{alert("Unable to save file request: "+e),console.error("Error:",e),document.getElementById("b_fr_save").disabled=!1})}function checkMaxNumber(e){if(e.value==""){e.value="1";return}let t=e.getAttribute("max");if(t=="")return;e.value>t&&(e.value=t)}function insertOrReplaceFileRequest(e){const n=document.getElementById("filerequesttable");let t=document.getElementById(`row-${e.id}`);if(t){const n=document.getElementById(`cell-username-${e.id}`).innerText;t.replaceWith(createFileRequestRow(e,n))}else{let t=createFileRequestRow(e,userName);t.querySelectorAll("td").forEach(e=>{e.classList.add("newFileRequest"),setTimeout(()=>{e.classList.remove("newFileRequest")},700)}),n.prepend(t)}}function createFileRequestRow(e,t){function u(e){const t=document.createElement("td");return t.textContent=e,t}function p(e,t,n){const o=document.createElement("td"),s=document.createElement("a");return s.textContent=e,s.href=t,s.id=n,s.target="_blank",o.appendChild(s),o}function c(e){const t=document.createElement("i");return t.className=`bi ${e}`,t}const f=`${baseUrl}publicUpload?id=${e.id}&key=${e.apikey}`,n=document.createElement("tr");n.id=`row-${e.id}`,n.className="filerequest-item",n.appendChild(p(e.name,f,`rqName-${e.id}`));const r=document.createElement("td"),h=document.createElement("span");if(h.id=`totalFiles-fr-${e.id}`,h.title="Uploaded files",h.textContent=e.uploadedfiles,r.appendChild(h),e.maxfiles!=0){r.appendChild(document.createTextNode(" / "));const t=document.createElement("span");t.title="File limit",t.textContent=e.maxfiles,r.appendChild(t)}if(e.uploadedfiles>0){r.appendChild(document.createTextNode(" "));const t=document.createElement("button");t.type="button",t.className="btn btn-sm btn-link text-light p-0 collapse-toggle",t.setAttribute("data-bs-toggle","collapse"),t.setAttribute("data-bs-target",`#collapse-filelist-${e.id}`),t.setAttribute("aria-expanded","false"),t.setAttribute("aria-controls",`collapse-filelist-${e.id}`),t.title="Expand / Collapse",t.appendChild(c("bi-chevron-down")),r.appendChild(t)}if(n.appendChild(r),n.appendChild(u(getReadableSize(e.totalfilesize))),n.appendChild(u(formatTimestampWithNegative(e.lastupload,"None"))),n.appendChild(u(formatFileRequestExpiry(e.expiry))),canViewOtherRequests){let s=u(t);s.id=`cell-username-${e.id}`,n.appendChild(s)}const m=document.createElement("td"),d=document.createElement("div");d.className="btn-toolbar justify-content-end",d.setAttribute("role","toolbar");const l=document.createElement("div");l.className="btn-group",l.setAttribute("role","group");const a=document.createElement("button");a.id=`download-${e.id}`,a.type="button",a.className="btn btn-outline-light btn-sm",a.title="Download all",e.uploadedfiles==0&&a.classList.add("disabled"),a.appendChild(c("bi-download"));const i=document.createElement("button");i.id=`copy-${e.id}`,i.type="button",i.className="copyurl btn btn-outline-light btn-sm",i.title="Copy URL",i.setAttribute("data-clipboard-text",f),i.onclick=()=>showToast(1e3),i.appendChild(c("bi-copy"));const o=document.createElement("button");o.id=`edit-${e.id}`,o.type="button",o.className="btn btn-outline-light btn-sm",o.title="Edit request",o.onclick=()=>editFileRequest(e.id,e.name,e.maxfiles,e.maxsize,e.expiry,e.notes),t!=userName&&!canEditOtherRequests&&(o.disabled=!0),o.appendChild(c("bi-pencil"));const s=document.createElement("button");return s.id=`delete-${e.id}`,s.type="button",s.className="btn btn-outline-danger btn-sm",s.title="Delete",s.onclick=()=>deleteOrShowModal(e.id,e.name),t!=userName&&!canDeleteOtherRequests&&(s.disabled=!0),s.appendChild(c("bi-trash3")),l.append(a,i,o,s),d.appendChild(l),m.appendChild(d),n.appendChild(m),n}function filterLogs(e){const t=document.getElementById("logviewer");e=="all"?t.value=logContent:t.value=logContent.split(` +const storedTokens=new Map;async function getToken(e,t){const n="./auth/token";if(!t){if(!storedTokens.has(e))return getToken(e,!0);let t=storedTokens.get(e);return t.expiry-Date.now()/1e3<60?getToken(e,!0):t.key}const s={method:"POST",headers:{"Content-Type":"application/json",permission:e}};try{const o=await fetch(n,s);if(!o.ok)throw new Error(`Request failed with status: ${o.status}`);const t=await o.json();if(!t.hasOwnProperty("key"))throw new Error(`Invalid response when trying to get token`);return storedTokens.set(e,{key:t.key,expiry:t.expiry}),t.key}catch(e){throw console.error("Error in getToken:",e),e}}async function apiAuthModify(e,t,n){const o="./api/auth/modify",i="PERM_API_MOD";let s;try{s=await getToken(i,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const a={method:"POST",headers:{"Content-Type":"application/json",apikey:s,targetKey:e,permission:t,permissionModifier:n}};try{const e=await fetch(o,a);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiAuthModify:",e),e}}async function apiAuthFriendlyName(e,t){const s="./api/auth/friendlyname",o="PERM_API_MOD";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"PUT",headers:{"Content-Type":"application/json",apikey:n,targetKey:e,friendlyName:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiAuthModify:",e),e}}async function apiAuthDelete(e){const n="./api/auth/delete",s="PERM_API_MOD";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t,targetKey:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiAuthDelete:",e),e}}async function apiAuthCreate(){const t="./api/auth/create",n="PERM_API_MOD";let e;try{e=await getToken(n,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const s={method:"POST",headers:{"Content-Type":"application/json",apikey:e,basicPermissions:"true"}};try{const e=await fetch(t,s);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const n=await e.json();return n}catch(e){throw console.error("Error in apiAuthCreate:",e),e}}async function apiChunkComplete(e,t,n,s,o,i,a,r,c,l){const u="./api/chunk/complete",h="PERM_UPLOAD";let d;try{d=await getToken(h,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const m={method:"POST",headers:{"Content-Type":"application/json",apikey:d,uuid:e,filename:"base64:"+Base64.encode(t),filesize:n,realsize:s,contenttype:o,allowedDownloads:i,expiryDays:a,password:r,isE2E:c,nonblocking:l}};try{const e=await fetch(u,m);if(!e.ok){let t;try{const n=await e.json();t=n.ErrorMessage||`Request failed with status: ${e.status}`}catch{const n=await e.text();t=n||`Request failed with status: ${e.status}`}throw new Error(t)}const t=await e.json();return t}catch(e){throw console.error("Error in apiChunkComplete:",e),e}}async function apiFilesReplace(e,t){const s="./api/files/replace",o="PERM_REPLACE";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"PUT",headers:{"Content-Type":"application/json",id:e,apikey:n,idNewContent:t,deleteNewFile:!1}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesReplace:",e),e}}async function apiFilesListById(e){const n="./api/files/list/"+e,s="PERM_VIEW";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"GET",headers:{"Content-Type":"application/json",apikey:t}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesListById:",e),e}}async function apiFilesListDownloadSingle(e){const n="./api/files/download/"+e,s="PERM_DOWNLOAD";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"GET",headers:{"Content-Type":"application/json",apikey:t,presignUrl:!0}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesListDownloadSingle:",e),e}}async function apiFilesListDownloadZip(e,t,n){const o="./api/files/downloadzip",i="PERM_DOWNLOAD";let s;try{s=await getToken(i,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const a={method:"GET",headers:{"Content-Type":"application/json",apikey:s,ids:e,filename:"base64:"+Base64.encode(n),isFileRequestId:t,presignUrl:!0}};try{const e=await fetch(o,a);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesListDownloadZip:",e),e}}async function apiFilesModify(e,t,n,s,o){const a="./api/files/modify",r="PERM_EDIT";let i;try{i=await getToken(r,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const c={method:"PUT",headers:{"Content-Type":"application/json",id:e,apikey:i,allowedDownloads:t,expiryTimestamp:n,password:s,originalPassword:o}};try{const e=await fetch(a,c);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesModify:",e),e}}async function apiFilesDelete(e,t){const s="./api/files/delete",o="PERM_DELETE";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"POST",headers:{"Content-Type":"application/json",apikey:n,id:e,delay:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiFilesDelete:",e),e}}async function apiFilesRestore(e){const n="./api/files/restore",s="PERM_DELETE";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t,id:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiFilesRestore:",e),e}}async function apiUserCreate(e){const n="./api/user/create",s="PERM_MANAGE_USERS";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t,username:e}};try{const e=await fetch(n,o);if(!e.ok)throw e.status==409?new Error("duplicate"):new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiUserModify:",e),e}}async function apiUserModify(e,t,n){const o="./api/user/modify",i="PERM_MANAGE_USERS";let s;try{s=await getToken(i,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const a={method:"POST",headers:{"Content-Type":"application/json",apikey:s,userid:e,userpermission:t,permissionModifier:n}};try{const e=await fetch(o,a);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiUserModify:",e),e}}async function apiUserChangeRank(e,t){const s="./api/user/changeRank",o="PERM_MANAGE_USERS";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"POST",headers:{"Content-Type":"application/json",apikey:n,userid:e,newRank:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiUserModify:",e),e}}async function apiUserDelete(e,t){const s="./api/user/delete",o="PERM_MANAGE_USERS";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"POST",headers:{"Content-Type":"application/json",apikey:n,userid:e,deleteFiles:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiUserDelete:",e),e}}async function apiUserResetPassword(e,t){const s="./api/user/resetPassword",o="PERM_MANAGE_USERS";let n;try{n=await getToken(o,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const i={method:"POST",headers:{"Content-Type":"application/json",apikey:n,userid:e,generateNewPassword:t}};try{const e=await fetch(s,i);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiUserResetPassword:",e),e}}async function apiLogSystemStatus(){const t="./api/logs/systemStatus",n="PERM_MANAGE_LOGS";let e;try{e=await getToken(n,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const s={method:"GET",headers:{"Content-Type":"application/json",apikey:e}};try{const e=await fetch(t,s);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const n=await e.json();return n}catch(e){throw console.error("Error in apiLogSystemStatus:",e),e}}async function apiLogResetTraffic(){const t="./api/logs/resetTraffic",n="PERM_MANAGE_LOGS";let e;try{e=await getToken(n,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const s={method:"GET",headers:{"Content-Type":"application/json",apikey:e}};try{const e=await fetch(t,s);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiLogResetTraffic:",e),e}}async function apiLogGet(e){const n="./api/logs/get",s="PERM_MANAGE_LOGS";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"GET",headers:{"Content-Type":"application/json",apikey:t,timestamp:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiLogGet:",e),e}}async function apiLogsDelete(e){const n="./api/logs/delete",s="PERM_MANAGE_LOGS";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t,timestamp:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiLogsDelete:",e),e}}async function apiE2eGet(){const t="./api/e2e/get",n="PERM_UPLOAD";let e;try{e=await getToken(n,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const s={method:"POST",headers:{"Content-Type":"application/json",apikey:e}};try{const e=await fetch(t,s);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);return await e.text()}catch(e){throw console.error("Error in apiE2eGet:",e),e}}async function apiE2eMutexLockUnlock(e){let t="./api/e2e/mutex/lock";e&&(t="./api/e2e/mutex/unlock");const s="PERM_UPLOAD";let n;try{n=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"GET",headers:{"Content-Type":"application/json",apikey:n}};try{const e=await fetch(t,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);return await e.text()}catch(e){throw console.error("Error in apiE2eMutexLock:",e),e}}async function apiE2eStore(e){const n="./api/e2e/set",s="PERM_UPLOAD";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"POST",headers:{"Content-Type":"application/json",apikey:t},body:JSON.stringify({content:e})};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiE2eStore:",e),e}}async function apiURequestDelete(e){const n="./api/uploadrequest/delete",s="PERM_MANAGE_FILE_REQUESTS,PERM_DELETE";let t;try{t=await getToken(s,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const o={method:"DELETE",headers:{"Content-Type":"application/json",apikey:t,id:e}};try{const e=await fetch(n,o);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`)}catch(e){throw console.error("Error in apiURequestDelete:",e),e}}async function apiURequestSave(e,t,n,s,o,i){const r="./api/uploadrequest/save",c="PERM_MANAGE_FILE_REQUESTS";let a;try{a=await getToken(c,!1)}catch(e){throw console.error("Unable to gain permission token:",e),e}const l={method:"POST",headers:{"Content-Type":"application/json",apikey:a,id:e,name:"base64:"+Base64.encode(t),expiry:o,maxfiles:n,maxsize:s,notes:"base64:"+Base64.encode(i)}};try{const e=await fetch(r,l);if(!e.ok)throw new Error(`Request failed with status: ${e.status}`);const t=await e.json();return t}catch(e){throw console.error("Error in apiURequestDelete:",e),e}}try{var toastId,calendarInstance,dropzoneObject,isE2EEnabled,isUploading,rowCount,sseWorkerPort,statusItemCount,clipboard=new ClipboardJS(".copyurl")}catch{}function showToast(e,t){let n=document.getElementById("toastnotification");typeof t!="undefined"?n.innerText=t:n.innerText=n.dataset.default,n.classList.add("show"),clearTimeout(toastId),toastId=setTimeout(()=>{hideToast()},e)}function hideToast(){document.getElementById("toastnotification").classList.remove("show")}calendarInstance=null;function createCalendar(e,t,n){const o=new Date(t*1e3);let s={enableTime:!0,dateFormat:"U",altInput:!0,altFormat:"Y-m-d H:i",allowInput:!0,time_24hr:!0,defaultDate:o,minDate:"today"};n&&(s.maxDate=new Date(n*1e3)),calendarInstance=flatpickr(document.getElementById(e),s)}function handleEditCheckboxChange(e){var t=document.getElementById(e.getAttribute("data-toggle-target")),n=e.getAttribute("data-timestamp");e.checked?(t.classList.remove("disabled"),t.removeAttribute("disabled"),n!=null&&(calendarInstance._input.disabled=!1)):(n!=null&&(calendarInstance._input.disabled=!0),t.classList.add("disabled"),t.setAttribute("disabled",!0))}function downloadFileWithPresign(e){apiFilesListDownloadSingle(e).then(e=>{if(!e.hasOwnProperty("downloadUrl"))throw new Error("Unable to get presigned key");const t=document.createElement("a");t.href=e.downloadUrl,t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}).catch(e=>{alert("Unable to download: "+e),console.error("Error:",e)})}function downloadFilesZipWithPresign(e,t,n){apiFilesListDownloadZip(e,t,n).then(e=>{if(!e.hasOwnProperty("downloadUrl"))throw new Error("Unable to get presigned key");const t=document.createElement("a");t.href=e.downloadUrl,t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}).catch(e=>{alert("Unable to download: "+e),console.error("Error:",e)})}function doLogout(){typeof sseWorkerPort!="undefined"&&sseWorkerPort!==null&&sseWorkerPort.postMessage({type:"shutdown"}),window.location.href="./logout"}function changeApiPermission(e,t,n){var o,i,s=document.getElementById(n);if(s.classList.contains("perm-processing")||s.classList.contains("perm-nochange"))return;o=s.classList.contains("perm-granted"),s.classList.add("perm-processing"),s.classList.remove("perm-granted"),s.classList.remove("perm-notgranted"),i="GRANT",o&&(i="REVOKE"),apiAuthModify(e,t,i).then(e=>{o?(s.classList.add("perm-notgranted"),s.classList.add("perm-nownotgranted")):(s.classList.add("perm-granted"),s.classList.add("perm-nowgranted")),s.classList.remove("perm-processing"),setTimeout(()=>{s.classList.remove("perm-nowgranted"),s.classList.remove("perm-nownotgranted")},1e3)}).catch(e=>{o?s.classList.add("perm-granted"):s.classList.add("perm-notgranted"),s.classList.remove("perm-processing"),alert("Unable to set permission: "+e),console.error("Error:",e)})}function deleteApiKey(e){document.getElementById("delete-"+e).disabled=!0,apiAuthDelete(e).then(t=>{document.getElementById("row-"+e).classList.add("rowDeleting"),setTimeout(()=>{document.getElementById("row-"+e).remove()},290)}).catch(e=>{alert("Unable to delete API key: "+e),console.error("Error:",e)})}function newApiKey(){document.getElementById("button-newapi").disabled=!0,apiAuthCreate().then(e=>{addRowApi(e.Id,e.PublicId),document.getElementById("button-newapi").disabled=!1}).catch(e=>{alert("Unable to create API key: "+e),console.error("Error:",e)})}function addFriendlyNameChange(e){let t=document.getElementById("friendlyname-"+e);if(t.classList.contains("isBeingEdited"))return;t.classList.add("isBeingEdited");let i=t.innerText,n=document.createElement("input");n.size=5,n.value=i;let s=!0,o=function(){if(!s)return;s=!1;let o=n.value;o==""&&(o="Unnamed key"),t.innerText=o,t.classList.remove("isBeingEdited"),apiAuthFriendlyName(e,o).catch(e=>{alert("Unable to save name: "+e),console.error("Error:",e)})};n.onblur=o,n.addEventListener("keyup",function(e){e.keyCode===13&&(e.preventDefault(),o())}),t.innerText="",t.appendChild(n),n.focus()}function addRowApi(e,t){let p=document.getElementById("apitable"),s=p.insertRow(0);s.id="row-"+t;let i=0,c=s.insertCell(i++),l=s.insertCell(i++),d=s.insertCell(i++),a=s.insertCell(i++),u;canViewOtherApiKeys&&(u=s.insertCell(i++));let h=s.insertCell(i++);canViewOtherApiKeys&&(u.classList.add("newApiKey"),u.innerText=userName),c.classList.add("newApiKey"),l.classList.add("newApiKey"),d.classList.add("newApiKey"),a.classList.add("newApiKey"),a.classList.add("prevent-select"),h.classList.add("newApiKey"),c.innerText="Unnamed key",c.id="friendlyname-"+t,c.onclick=function(){addFriendlyNameChange(t)},l.innerText=e,l.classList.add("font-monospace"),d.innerText="Never";const r=document.createElement("div");r.className="btn-group",r.setAttribute("role","group");const n=document.createElement("button");n.type="button",n.dataset.clipboardText=e,n.title="Copy API Key",n.className="copyurl btn btn-outline-light btn-sm",n.setAttribute("onclick","showToast(1000)");const m=document.createElement("i");m.className="bi bi-copy",n.appendChild(m);const o=document.createElement("button");o.type="button",o.id=`delete-${t}`,o.title="Delete",o.className="btn btn-outline-danger btn-sm",o.setAttribute("onclick",`deleteApiKey('${t}')`);const f=document.createElement("i");f.className="bi bi-trash3",o.appendChild(f),r.appendChild(n),r.appendChild(o),h.appendChild(r);const g=[{perm:"PERM_VIEW",icon:"bi-eye",granted:!0,title:"List Uploads"},{perm:"PERM_UPLOAD",icon:"bi-file-earmark-plus",granted:!0,title:"Upload"},{perm:"PERM_EDIT",icon:"bi-pencil",granted:!0,title:"Edit Uploads"},{perm:"PERM_DELETE",icon:"bi-trash3",granted:!0,title:"Delete Uploads"},{perm:"PERM_REPLACE",icon:"bi-recycle",granted:!1,title:"Replace Uploads"},{perm:"PERM_DOWNLOAD",icon:"bi-box-arrow-in-down",granted:!1,title:"Download Files"},{perm:"PERM_MANAGE_FILE_REQUESTS",icon:"bi-file-earmark-arrow-up",granted:!1,title:"Manage File Requests"},{perm:"PERM_MANAGE_USERS",icon:"bi-people",granted:!1,title:"Manage Users"},{perm:"PERM_MANAGE_LOGS",icon:"bi-card-list",granted:!1,title:"Manage System Logs"},{perm:"PERM_API_MOD",icon:"bi-sliders2",granted:!1,title:"Manage API Keys"}];if(g.forEach(({perm:e,icon:n,granted:s,title:o})=>{const i=document.createElement("i"),r=`${e.toLowerCase()}_${t}`;i.id=r,i.className=`bi ${n} ${s?"perm-granted":"perm-notgranted"}`,i.title=o,i.setAttribute("onclick",`changeApiPermission("${t}","${e}", "${r}");`),a.appendChild(i),a.appendChild(document.createTextNode(" "))}),!canReplaceFiles){let e=document.getElementById("perm_replace_"+t);e.classList.add("perm-unavailable"),e.classList.add("perm-nochange")}if(!canManageUsers){let e=document.getElementById("perm_manage_users_"+t);e.classList.add("perm-unavailable"),e.classList.add("perm-nochange")}if(!canViewSystemLog){let e=document.getElementById("perm_manage_logs_"+t);e.classList.add("perm-unavailable"),e.classList.add("perm-nochange")}if(!canCreateFileRequest){let e=document.getElementById("perm_manage_file_requests_"+t);e.classList.add("perm-unavailable"),e.classList.add("perm-nochange")}setTimeout(()=>{c.classList.remove("newApiKey"),l.classList.remove("newApiKey"),d.classList.remove("newApiKey"),a.classList.remove("newApiKey"),h.classList.remove("newApiKey")},700)}function deleteFileRequest(e){document.getElementById("delete-"+e).disabled=!0,apiURequestDelete(e).then(t=>{const s=document.getElementById("row-"+e),n=document.getElementById("filelist-"+e);s.classList.add("rowDeleting"),n!==null&&n.classList.add("rowDeleting"),setTimeout(()=>{s.remove(),n!==null&&n.remove()},290)}).catch(e=>{alert("Unable to delete file request: "+e),console.error("Error:",e)})}function deleteOrShowModal(e,t){const n=getFileRequestUploadCount(e);n===0?deleteFileRequest(e):showDeleteFRequestModal(e,t,n)}function deleteFileFr(e,t){document.getElementById("button-delete-"+e).disabled=!0;let n=document.getElementById("cell-listupload-"+e);apiFilesDelete(e,10).then(s=>{changeFileCountFr(t,-1),n.classList.add("rowDeleting"),setTimeout(()=>{n.remove()},290),updateDownloadButton(t),showToastFileDeletionFr(e)}).catch(e=>{alert("Unable to delete file: "+e),console.error("Error:",e)})}function changeFileCountFr(e,t){let n=document.getElementById("totalFiles-fr-"+e),s=getFileRequestUploadCount(e)+t;n.innerText=s}function getFileRequestUploadCount(e){let t=document.getElementById("totalFiles-fr-"+e);return Number(t.innerText)||0}function updateDownloadButton(e){const t=document.getElementById(`download-${e}`);if(!t)return;const n=document.getElementById("totalFiles-fr-"+e),o=n?n.innerText.split("+")[0].trim():"",s=Number(o)||0,i=t.getAttribute("onclick")||"";if(s===0){t.classList.add("disabled"),t.removeAttribute("onclick");return}if(s===1){let n=getFileIdsForFilerequest(e)[0];t.setAttribute("onclick",`downloadFileWithPresign('${n}');`)}}function getFileIdsForFilerequest(e){const t=document.querySelectorAll(`#collapse-filelist-${e} .filelist-item:not(.rowDeleting)`);return Array.from(t).map(e=>e.id.replace("cell-listupload-","")).filter(e=>e)}function showToastFileDeletionFr(e){let t=document.getElementById("toastnotificationUndo"),n=document.getElementById("cell-name-"+e).innerText,s=document.getElementById("toastFilename"),o=document.getElementById("toastUndoButton");s.innerText=n,o.dataset.fileid=e,hideToast(),t.classList.add("show"),clearTimeout(toastId),toastId=setTimeout(()=>{hideFileToast()},5e3)}function handleUndoFr(e){hideFileToast(),apiFilesRestore(e.dataset.fileid).then(e=>{window.location.reload()}).catch(e=>{alert("Unable to restore file: "+e),console.error("Error:",e)})}function showDeleteFRequestModal(e,t,n){document.getElementById("deleteModalBodyName").innerText=t,document.getElementById("deleteModalBodyCount").innerText=n,$("#deleteModal").modal("show"),document.getElementById("buttonDelete").onclick=function(){$("#deleteModal").modal("hide"),deleteFileRequest(e)}}function newFileRequest(){loadFileRequestDefaults(),document.getElementById("m_urequestlabel").innerText="New File Request",$("#addEditModal").modal("show"),document.getElementById("b_fr_save").onclick=function(){saveFileRequestDefaults(),saveFileRequest(),$("#addEditModal").modal("hide")}}function saveFileRequestDefaults(){if(document.getElementById("mc_maxfiles").checked?localStorage.setItem("fr_maxfiles",document.getElementById("mi_maxfiles").value):localStorage.setItem("fr_maxfiles",0),document.getElementById("mc_maxsize").checked?localStorage.setItem("fr_maxsize",document.getElementById("mi_maxsize").value):localStorage.setItem("fr_maxsize",0),document.getElementById("mc_expiry").checked){let e=document.getElementById("mi_expiry").value-Math.round(Date.now()/1e3);localStorage.setItem("fr_expiry",e)}else localStorage.setItem("fr_expiry",0)}function loadFileRequestDefaults(){const t=localStorage.getItem("fr_maxfiles"),n=localStorage.getItem("fr_maxsize");let e=localStorage.getItem("fr_expiry");if(e!=="0"&&e!==null){let t=new Date(Date.now()+Number(e*1e3));t.setHours(12,0,0,0),e=Math.floor(t.getTime()/1e3)}setModalValues("","",t,n,e,"")}function setModalValues(e,t,n,s,o,i){if(document.getElementById("freqId").value=e,t===null?document.getElementById("mFriendlyName").value="":document.getElementById("mFriendlyName").value=t,limitMaxFiles!=0){let e=document.getElementById("mc_maxfiles");(n===null||n==0)&&(n=limitMaxFiles),e.checked=!0,e.disabled=!0,e.title="Only admins can set this to unlimited",e.value="1",document.getElementById("mi_maxfiles").setAttribute("max",limitMaxFiles)}else{let e=document.getElementById("mc_maxfiles");e.disabled=!1,e.title="",document.getElementById("mi_maxfiles").setAttribute("max","")}if(limitMaxSize!=0){let e=document.getElementById("mc_maxsize");(s===null||s==0)&&(s=limitMaxSize),e.checked=!0,e.disabled=!0,e.title="Only admins can set this to unlimited",e.value="1",document.getElementById("mi_maxsize").setAttribute("max",limitMaxSize)}else{let e=document.getElementById("mc_maxsize");e.disabled=!1,e.title="",document.getElementById("mi_maxsize").setAttribute("max","")}n===null||n==0?(document.getElementById("mi_maxfiles").value="1",document.getElementById("mi_maxfiles").disabled=!0,document.getElementById("mc_maxfiles").checked=!1):(document.getElementById("mi_maxfiles").value=n,document.getElementById("mi_maxfiles").disabled=!1,document.getElementById("mc_maxfiles").checked=!0),s===null||s==0?(document.getElementById("mi_maxsize").value="10",document.getElementById("mi_maxsize").disabled=!0,document.getElementById("mc_maxsize").checked=!1):(document.getElementById("mi_maxsize").value=s,document.getElementById("mi_maxsize").disabled=!1,document.getElementById("mc_maxsize").checked=!0);const c=Math.floor(new Date(Date.now()+14*24*60*60*1e3).getTime()/1e3);let r=0,a=document.getElementById("mc_expiry");maxExpirySeconds>0?(r=Math.floor(Date.now()/1e3)+maxExpirySeconds,o===null||o==0?o=Math.min(c,r):o>r&&(o=r),a.disabled=!0,a.title="The server limits the lifetime of files"):(a.disabled=!1,a.title="Expiry"),o===null||o==0?(document.getElementById("mi_expiry").disabled=!0,a.checked=!1,document.getElementById("mi_expiry").value=c,createCalendar("mi_expiry",c)):(document.getElementById("mi_expiry").value=o,document.getElementById("mi_expiry").disabled=!1,a.checked=!0,createCalendar("mi_expiry",o,r)),document.getElementById("mNotes").value=i}function editFileRequest(e,t,n,s,o,i){setModalValues(e,t,n,s,o,i),document.getElementById("m_urequestlabel").innerText="Edit File Request",$("#addEditModal").modal("show"),document.getElementById("b_fr_save").onclick=function(){saveFileRequest(),$("#addEditModal").modal("hide")}}function saveFileRequest(){const s=document.getElementById("b_fr_save"),o=document.getElementById("freqId").value,i=document.getElementById("mFriendlyName").value,a=document.getElementById("mNotes").value;let e=0,t=0,n=0;document.getElementById("mc_maxfiles").checked&&(e=document.getElementById("mi_maxfiles").value),document.getElementById("mc_maxsize").checked&&(t=document.getElementById("mi_maxsize").value),document.getElementById("mc_expiry").checked&&(n=document.getElementById("mi_expiry").value),s.disabled=!0,apiURequestSave(o,i,e,t,n,a).then(e=>{document.getElementById("b_fr_save").disabled=!1,insertOrReplaceFileRequest(e)}).catch(e=>{alert("Unable to save file request: "+e),console.error("Error:",e),document.getElementById("b_fr_save").disabled=!1})}function checkMaxNumber(e){if(e.value==""){e.value="1";return}let t=e.getAttribute("max");if(t=="")return;e.value>t&&(e.value=t)}function insertOrReplaceFileRequest(e){const n=document.getElementById("filerequesttable");let t=document.getElementById(`row-${e.id}`);if(t){const n=document.getElementById(`cell-username-${e.id}`).innerText;t.replaceWith(createFileRequestRow(e,n))}else{let t=createFileRequestRow(e,userName);t.querySelectorAll("td").forEach(e=>{e.classList.add("newFileRequest"),setTimeout(()=>{e.classList.remove("newFileRequest")},700)}),n.prepend(t)}}function createFileRequestRow(e,t){function u(e){const t=document.createElement("td");return t.textContent=e,t}function p(e,t,n){const o=document.createElement("td"),s=document.createElement("a");return s.textContent=e,s.href=t,s.id=n,s.target="_blank",o.appendChild(s),o}function c(e){const t=document.createElement("i");return t.className=`bi ${e}`,t}const f=`${baseUrl}publicUpload?id=${e.id}&key=${e.apikey}`,n=document.createElement("tr");n.id=`row-${e.id}`,n.className="filerequest-item",n.appendChild(p(e.name,f,`rqName-${e.id}`));const r=document.createElement("td"),h=document.createElement("span");if(h.id=`totalFiles-fr-${e.id}`,h.title="Uploaded files",h.textContent=e.uploadedfiles,r.appendChild(h),e.maxfiles!=0){r.appendChild(document.createTextNode(" / "));const t=document.createElement("span");t.title="File limit",t.textContent=e.maxfiles,r.appendChild(t)}if(e.uploadedfiles>0){r.appendChild(document.createTextNode(" "));const t=document.createElement("button");t.type="button",t.className="btn btn-sm btn-link text-light p-0 collapse-toggle",t.setAttribute("data-bs-toggle","collapse"),t.setAttribute("data-bs-target",`#collapse-filelist-${e.id}`),t.setAttribute("aria-expanded","false"),t.setAttribute("aria-controls",`collapse-filelist-${e.id}`),t.title="Expand / Collapse",t.appendChild(c("bi-chevron-down")),r.appendChild(t)}if(n.appendChild(r),n.appendChild(u(getReadableSize(e.totalfilesize))),n.appendChild(u(formatTimestampWithNegative(e.lastupload,"None"))),n.appendChild(u(formatFileRequestExpiry(e.expiry))),canViewOtherRequests){let s=u(t);s.id=`cell-username-${e.id}`,n.appendChild(s)}const m=document.createElement("td"),d=document.createElement("div");d.className="btn-toolbar justify-content-end",d.setAttribute("role","toolbar");const l=document.createElement("div");l.className="btn-group",l.setAttribute("role","group");const a=document.createElement("button");a.id=`download-${e.id}`,a.type="button",a.className="btn btn-outline-light btn-sm",a.title="Download all",e.uploadedfiles==0&&a.classList.add("disabled"),a.appendChild(c("bi-download"));const i=document.createElement("button");i.id=`copy-${e.id}`,i.type="button",i.className="copyurl btn btn-outline-light btn-sm",i.title="Copy URL",i.setAttribute("data-clipboard-text",f),i.onclick=()=>showToast(1e3),i.appendChild(c("bi-copy"));const o=document.createElement("button");o.id=`edit-${e.id}`,o.type="button",o.className="btn btn-outline-light btn-sm",o.title="Edit request",o.onclick=()=>editFileRequest(e.id,e.name,e.maxfiles,e.maxsize,e.expiry,e.notes),t!=userName&&!canEditOtherRequests&&(o.disabled=!0),o.appendChild(c("bi-pencil"));const s=document.createElement("button");return s.id=`delete-${e.id}`,s.type="button",s.className="btn btn-outline-danger btn-sm",s.title="Delete",s.onclick=()=>deleteOrShowModal(e.id,e.name),t!=userName&&!canDeleteOtherRequests&&(s.disabled=!0),s.appendChild(c("bi-trash3")),l.append(a,i,o,s),d.appendChild(l),m.appendChild(d),n.appendChild(m),n}function filterLogs(e){const t=document.getElementById("logviewer");e=="all"?t.value=logContent:t.value=logContent.split(` `).filter(t=>t.includes("["+e+"]")).join(` -`),t.scrollTop=t.scrollHeight}function setTrafficInfo(e,t){insertReadableSizeTwoOutputs(e,"totalTraffic","totalTrafficUnit"),document.getElementById("cardTraffic").title="Traffic since "+formatUnixTimestamp(t)}function setMemoryUsage(e,t){insertReadableSizeTwoOutputs(t,"totalMemory","memoryUnit");let n=document.getElementById("memoryUnit").innerText;insertReadableSizeForcedUnit(e,"usedMemory",n)}function setDiskUsage(e,t){insertReadableSizeTwoOutputs(t,"totalDisk","diskUnit");let n=document.getElementById("diskUnit").innerText;insertReadableSizeForcedUnit(e,"usedDisk",n)}function formatDuration(e){const t=[{label:"y",value:31536e3},{label:"d",value:86400},{label:"h",value:3600},{label:"m",value:60},{label:"s",value:1}];let n=t.findIndex(t=>e>=t.value);(n===-1||t[n].label==="s")&&(n=t.findIndex(e=>e.label==="m"));const s=t[n],o=t[n+1],i=Math.floor(e/s.value),a=e%s.value,r=Math.floor(a/o.value);return`${i}${s.label} ${r}${o.label}`}function addUptime(){if(currentUptime>3600)return;setTimeout(()=>{++currentUptime,document.getElementById("uptime").innerText=formatDuration(currentUptime),addUptime()},1e3)}function setPercentageBar(e,t,n){let o=t;n!==0[0]&&(o=t/n*100);const s=document.getElementById(e);s.classList.remove("bg-success"),s.classList.remove("bg-warning"),s.classList.remove("bg-danger"),o<70&&s.classList.add("bg-success"),o>=70&&o<90&&s.classList.add("bg-warning"),o>=90&&s.classList.add("bg-danger"),s.style.width=o+"%"}async function loadLogs(e){const t=document.getElementById("logviewer");try{const n=await apiLogGet(e);lastLogUpdate=n.timestamp;let s=!0;if(e!=0){if(n.logEntries=="")return;s=allowScroll(),logContent=logContent+n.logEntries}else logContent=n.logEntries;filterLogs(document.getElementById("logFilter").value),s&&(t.scrollTop=t.scrollHeight)}catch(e){lastLogUpdate=0,console.error("Failed to load logs:",e),t.value="Error loading logs. See console for details."}}async function loadStatus(){try{const e=await apiLogSystemStatus();currentUptime=e.uptime,document.getElementById("labelCpu").innerText=e.cpuLoad+"%",document.getElementById("labelActiveFiles").innerText=e.activeFiles,setPercentageBar("barCpu",e.cpuLoad),setPercentageBar("barDisk",e.diskUsagePercentage),setPercentageBar("barMemory",e.memoryUsagePercentage),setMemoryUsage(e.memoryUsed,e.memoryTotal),setDiskUsage(e.diskUsed,e.diskTotal),setTrafficInfo(e.dataServed,e.trafficRecordingSince)}catch(e){console.error("Failed to server status:",e)}}async function pollInfo(){for(firstStart=!0;!0;)await loadLogs(lastLogUpdate),firstStart?firstStart=!1:await loadStatus(),await new Promise(e=>setTimeout(e,POLL_INTERVAL_S*1e3))}function allowScroll(){const e=document.getElementById("logviewer");return e.scrollTop+e.clientHeight>=e.scrollHeight-5}function deleteLogs(){const n=document.getElementById("deleteLogsSel");if(!n)return;const t=n.value;if(t=="none"||t=="")return;if(!confirm("Do you want to delete the selected logs?")){document.getElementById("deleteLogs").selectedIndex=0;return}let e=Math.floor(Date.now()/1e3);switch(t){case"all":e=0;break;case"2":e=e-2*24*60*60;break;case"7":e=e-7*24*60*60;break;case"14":e=e-14*24*60*60;break;case"30":e=e-30*24*60*60;break;default:return}apiLogsDelete(e).then(e=>{location.reload()}).catch(e=>{alert("Unable to delete logs: "+e),console.error("Error:",e)})}function resetTrafficStat(){if(!confirm("Do you want to reset the traffic statistics?"))return;apiLogResetTraffic().then(e=>{location.reload()}).catch(e=>{alert("Unable to reset stats: "+e),console.error("Error:",e)})}isE2EEnabled=!1,isUploading=!1,rowCount=-1;function initDropzone(){Dropzone.options.uploaddropzone={paramName:"file",dictDefaultMessage:"",createImageThumbnails:!1,chunksUploaded:function(e,t){sendChunkComplete(e,t)},init:function(){dropzoneObject=this,this.on("addedfile",e=>{e.upload.uuid=getUuid(),saveUploadDefaults(),addFileProgress(e)}),this.on("queuecomplete",function(){isUploading=!1}),this.on("sending",function(){isUploading=!0}),this.on("error",function(e,t,n){if(console.log(t),n){if(n.status===413){showError(e,"File too large to upload. If you are using a reverse proxy, make sure that the allowed body size is at least 70MB.");return}try{console.log(n),errInfo=JSON.parse(n.responseText),showError(e,"Error: "+errInfo.ErrorMessage)}catch{showError(e,"Error: "+n.responseText)}}else showError(e,"Error: "+t)}),this.on("uploadprogress",function(e,t,n){updateProgressbar(e,t,n)}),isE2EEnabled&&(dropzoneObject.disable(),setE2eUpload())}},document.onpaste=function(e){if(dropzoneObject.disabled)return;const n=document.activeElement;if(n&&(n.hasAttribute("data-allow-regular-paste")||n.hasAttribute("placeholder")))return;var t,s=(e.clipboardData||e.originalEvent.clipboardData).items;for(let e in s)t=s[e],t.kind==="file"&&dropzoneObject.addFile(t.getAsFile()),t.kind==="string"&&t.getAsString(function(e){const t=//gi;if(t.test(e)===!1){let t=new Blob([e],{type:"text/plain"}),n=new File([t],"Pasted Text.txt",{type:"text/plain",lastModified:new Date(0)});dropzoneObject.addFile(n)}})},window.addEventListener("beforeunload",e=>{isUploading&&(e.returnValue="Upload is still in progress. Do you want to close this page?")})}function updateProgressbar(e,t,n){let o=e.upload.uuid,i=document.getElementById(`us-container-${o}`);if(i==null||i.getAttribute("data-complete")==="true")return;let s=Math.round(t);s<0&&(s=0),s>100&&(s=100);let r=Date.now()-i.getAttribute("data-starttime"),c=n/(r/1e3)/1024/1024;document.getElementById(`us-progressbar-${o}`).style.width=s+"%";let a=Math.round(c*10)/10;Number.isNaN(a)||(document.getElementById(`us-progress-info-${o}`).innerText=s+"% - "+a+"MB/s")}function addFileProgress(e){addFileStatus(e.upload.uuid,e.upload.filename)}function setUploadDefaults(){let s=getLocalStorageWithDefault("defaultDownloads",1),o=getLocalStorageWithDefault("defaultExpiry",14),e=getLocalStorageWithDefault("defaultPassword",""),t=getLocalStorageWithDefault("defaultUnlimitedDownloads",!1)==="true",n=getLocalStorageWithDefault("defaultUnlimitedTime",!1)==="true";document.getElementById("allowedDownloads").value=s,document.getElementById("expiryDays").value=o,document.getElementById("password").value=e,document.getElementById("enableDownloadLimit").checked=!t,document.getElementById("enableTimeLimit").checked=!n,e===""?(document.getElementById("enablePassword").checked=!1,document.getElementById("password").disabled=!0):(document.getElementById("enablePassword").checked=!0,document.getElementById("password").disabled=!1),t&&(document.getElementById("allowedDownloads").disabled=!0),n&&(document.getElementById("expiryDays").disabled=!0)}function saveUploadDefaults(){localStorage.setItem("defaultDownloads",document.getElementById("allowedDownloads").value),localStorage.setItem("defaultExpiry",document.getElementById("expiryDays").value),localStorage.setItem("defaultPassword",document.getElementById("password").value),localStorage.setItem("defaultUnlimitedDownloads",!document.getElementById("enableDownloadLimit").checked),localStorage.setItem("defaultUnlimitedTime",!document.getElementById("enableTimeLimit").checked)}function getLocalStorageWithDefault(e,t){var n=localStorage.getItem(e);return n===null?t:n}function urlencodeFormData(e){let t="";function s(e){return encodeURIComponent(e).replace(/%20/g,"+")}for(var n of e.entries())typeof n[1]=="string"&&(t+=(t?"&":"")+s(n[0])+"="+s(n[1]));return t}function sendChunkComplete(e,t){let c=e.upload.uuid,n=e.name,s=e.size,l=e.size,o=e.type,i=document.getElementById("allowedDownloads").value,a=document.getElementById("expiryDays").value,d=document.getElementById("password").value,r=e.isEndToEndEncrypted===!0,u=!0;document.getElementById("enableDownloadLimit").checked||(i=0),document.getElementById("enableTimeLimit").checked||(a=0),r&&(s=e.sizeEncrypted,n="Encrypted File",o=""),apiChunkComplete(c,n,s,l,o,i,a,d,r,u).then(n=>{t();let s=document.getElementById(`us-progress-info-${e.upload.uuid}`);s!=null&&(s.innerText="In Queue...")}).catch(t=>{console.error("Error:",t),dropzoneUploadError(e,t)})}function dropzoneUploadError(e,t){e.accepted=!1,dropzoneObject._errorProcessing([e],t),showError(e,t)}function dropzoneGetFile(e){for(let t=0;t{addRow(n),notifyWorker({type:"fileAdded",item:n});let s=dropzoneGetFile(t);if(s==null)return;s.isEndToEndEncrypted===!0?apiE2eMutexLockUnlock(!1).then(()=>apiE2eGet()).then(n=>{let i=GokapiE2EInfoParse(n);if(i instanceof Error)throw i;let a=GokapiE2EAddFile(t,e,s.name);if(a instanceof Error)throw a;let o=GokapiE2EInfoEncrypt();if(o instanceof Error)throw o;return apiE2eStore(o)}).then(()=>{GokapiE2EDecryptMenu(),removeFileStatus(t)}).catch(e=>{s.accepted=!1,dropzoneObject._errorProcessing([s],e),console.error("Error:",e)}).finally(()=>{apiE2eMutexLockUnlock(!0).catch(e=>{console.error("Failed to release E2E mutex after write: "+e)})}):removeFileStatus(t)}).catch(e=>{let n=dropzoneGetFile(t);n!=null&&dropzoneUploadError(n,e),console.error("Error:",e)})}function parseProgressStatus(e){let n=document.getElementById(`us-container-${e.chunk_id}`);if(n==null)return;n.setAttribute("data-complete","true");let t;switch(e.upload_status){case 0:t="Processing file...";break;case 1:t="Saving file...";break;case 2:t="Finalising...",requestFileInfo(e.file_id,e.chunk_id);break;case 3:t="Error";let n=dropzoneGetFile(e.chunk_id);e.error_message==""&&(e.error_message="Server Error"),n!=null&&dropzoneUploadError(n,e.error_message);return;default:t="Unknown status";break}document.getElementById(`us-progress-info-${e.chunk_id}`).innerText=t}function showError(e,t){let n=e.upload.uuid;document.getElementById(`us-progressbar-${n}`).style.width="100%",document.getElementById(`us-progressbar-${n}`).style.backgroundColor="red",document.getElementById(`us-progress-info-${n}`).innerText=t,document.getElementById(`us-progress-info-${n}`).classList.add("uploaderror")}function editFile(){const e=document.getElementById("mb_save");e.disabled=!0;let s=e.getAttribute("data-fileid"),o=document.getElementById("mi_edit_down").value,i=document.getElementById("mi_edit_expiry").value,t=document.getElementById("mi_edit_pw").value,a=t==="(unchanged)";document.getElementById("mc_download").checked||(o=0),document.getElementById("mc_expiry").checked||(i=0),document.getElementById("mc_password").checked||(a=!1,t="");let r=!1,n="";document.getElementById("mc_replace").checked&&(n=document.getElementById("mi_edit_replace").value,r=n!=""),apiFilesModify(s,o,i,t,a).then(t=>{if(!r){location.reload();return}apiFilesReplace(s,n).then(e=>{location.reload()}).catch(t=>{alert("Unable to edit file: "+t),console.error("Error:",t),e.disabled=!1})}).catch(t=>{alert("Unable to edit file: "+t),console.error("Error:",t),e.disabled=!1})}function showEditModal(e,t,n,s,o,i,a,r,c){let d=$("#modaledit").clone();$("#modaledit").on("hide.bs.modal",function(){$("#modaledit").remove();let e=d.clone();$("body").append(e)}),document.getElementById("m_filenamelabel").innerText=e,document.getElementById("mc_expiry").setAttribute("data-timestamp",s),document.getElementById("mb_save").setAttribute("data-fileid",t),createCalendar("mi_edit_expiry",s),i?(document.getElementById("mi_edit_down").value="1",document.getElementById("mi_edit_down").disabled=!0,document.getElementById("mc_download").checked=!1):(document.getElementById("mi_edit_down").value=n,document.getElementById("mi_edit_down").disabled=!1,document.getElementById("mc_download").checked=!0),a?(document.getElementById("mi_edit_expiry").value=add14DaysIfBeforeCurrentTime(s),document.getElementById("mi_edit_expiry").disabled=!0,document.getElementById("mc_expiry").checked=!1,calendarInstance._input.disabled=!0):(document.getElementById("mi_edit_expiry").value=s,document.getElementById("mi_edit_expiry").disabled=!1,document.getElementById("mc_expiry").checked=!0,calendarInstance._input.disabled=!1),o?(document.getElementById("mi_edit_pw").value="(unchanged)",document.getElementById("mi_edit_pw").disabled=!1,document.getElementById("mc_password").checked=!0):(document.getElementById("mi_edit_pw").value="",document.getElementById("mi_edit_pw").disabled=!0,document.getElementById("mc_password").checked=!1);let l=document.getElementById("mi_edit_replace");if(c)if(document.getElementById("replaceGroup").style.display="flex",r)document.getElementById("mc_replace").disabled=!0,document.getElementById("mc_replace").title="Replacing content is not available for end-to-end encrypted files",l.add(new Option("Unavailable",0)),l.title="Replacing content is not available for end-to-end encrypted files",l.value="0";else{let e=getAllAvailableFiles();for(let n=0;n{changeRowCount(!1,document.getElementById("row-"+e)),showToastFileDeletion(e),notifyWorker({type:"fileDeleted",id:e})}).catch(e=>{alert("Unable to delete file: "+e),console.error("Error:",e)})}function checkBoxChanged(e,t){let n=!e.checked;n?document.getElementById(t).setAttribute("disabled",""):document.getElementById(t).removeAttribute("disabled"),t==="password"&&n&&(document.getElementById("password").value="")}function parseSseData(e){let t;try{t=JSON.parse(e)}catch(e){console.error("Failed to parse event data:",e);return}switch(t.event){case"download":setNewDownloadCount(t.file_id,t.download_count,t.downloads_remaining);return;case"uploadStatus":parseProgressStatus(t);return;default:console.error("Unknown event",t)}}function setNewDownloadCount(e,t,n){let s=document.getElementById("cell-downloads-"+e);if(s!=null&&(s.innerText=t,s.classList.add("updatedDownloadCount"),setTimeout(()=>s.classList.remove("updatedDownloadCount"),500)),n!=-1){let t=document.getElementById("cell-downloadsRemaining-"+e);t!=null&&(t.innerText=n,t.classList.add("updatedDownloadCount"),setTimeout(()=>t.classList.remove("updatedDownloadCount"),500))}}sseWorkerPort=null;function notifyWorker(e){sseWorkerPort!==null&&sseWorkerPort.postMessage(e)}function registerChangeHandler(){if(typeof SharedWorker!="undefined")try{const e=new SharedWorker("./js/sse-worker.js");e.port.onmessage=e=>{if(e.data.type==="message")parseSseData(e.data.data);else if(e.data.type==="error")console.error("SSE worker connection error:",e.data.detail);else if(e.data.type==="shutdown")setTimeout(function(){window.location.href="./logout_auto"},1e3);else if(e.data.type==="fileAdded")document.getElementById("row-"+sanitizeId(e.data.item.Id))==null&&addRow(e.data.item);else if(e.data.type==="fileDeleted"){let t=document.getElementById("row-"+sanitizeId(e.data.id));t!=null&&changeRowCount(!1,t)}else if(e.data.type==="log"){const{level:t,message:n,detail:s}=e.data;s?console[t](n,s):console[t](n)}},e.onerror=e=>{console.warn("SharedWorker failed, falling back to direct SSE:",e),sseWorkerPort=null,_registerDirectSSE()},e.port.start(),sseWorkerPort=e.port;return}catch(e){console.warn("SharedWorker unavailable, falling back to direct SSE:",e)}_registerDirectSSE()}function _registerDirectSSE(){const e=new EventSource("./uploadStatus");e.onmessage=e=>{parseSseData(e.data)},e.onerror=t=>{t.target.readyState!==EventSource.CLOSED&&e.close(),console.log("Reconnecting to SSE (direct)..."),setTimeout(_registerDirectSSE,5e3)}}statusItemCount=0;function addFileStatus(e,t){const n=document.createElement("div");n.setAttribute("id",`us-container-${e}`),n.classList.add("us-container");const a=document.createElement("div");a.classList.add("filename"),a.textContent=t,n.appendChild(a);const s=document.createElement("div");s.classList.add("upload-progress-container"),s.setAttribute("id",`us-progress-container-${e}`);const r=document.createElement("div");r.classList.add("upload-progress-bar");const o=document.createElement("div");o.setAttribute("id",`us-progressbar-${e}`),o.classList.add("upload-progress-bar-progress"),o.style.width="0%",r.appendChild(o);const i=document.createElement("div");i.setAttribute("id",`us-progress-info-${e}`),i.classList.add("upload-progress-info"),i.textContent="0%",s.appendChild(r),s.appendChild(i),n.appendChild(s),n.setAttribute("data-starttime",Date.now()),n.setAttribute("data-complete","false");const c=document.getElementById("uploadstatus");c.appendChild(n),c.style.visibility="visible",statusItemCount++}function removeFileStatus(e){const t=document.getElementById(`us-container-${e}`);if(t==null)return;t.remove(),statusItemCount--,statusItemCount<1&&(document.getElementById("uploadstatus").style.visibility="hidden")}function addRow(e){let d=document.getElementById("downloadtable"),t=d.insertRow(0);e.Id=sanitizeId(e.Id),t.id="row-"+e.Id;let i=t.insertCell(0),a=t.insertCell(1),s=t.insertCell(2),r=t.insertCell(3),c=t.insertCell(4),o=t.insertCell(5),l=t.insertCell(6);i.innerText=e.Name,i.id="cell-name-"+e.Id,c.id="cell-downloads-"+e.Id,a.innerText=e.Size,e.UnlimitedDownloads?s.innerText="Unlimited":(s.innerText=e.DownloadsRemaining,s.id="cell-downloadsRemaining-"+e.Id),e.UnlimitedTime?r.innerText="Unlimited":r.innerText=formatUnixTimestamp(e.ExpireAt),c.innerText=e.DownloadCount;const n=document.createElement("a");if(n.href=e.UrlDownload,n.target="_blank",n.style.color="inherit",n.id="url-href-"+e.Id,n.textContent=e.Id,o.appendChild(n),e.IsPasswordProtected===!0){const e=document.createElement("i");e.className="bi bi-key",e.title="Password protected",o.appendChild(document.createTextNode(" ")),o.appendChild(e)}return l.appendChild(createButtonGroup(e)),i.classList.add("newItem"),a.classList.add("newItem"),s.classList.add("newItem"),r.classList.add("newItem"),c.classList.add("newItem"),o.classList.add("newItem"),l.classList.add("newItem"),a.setAttribute("data-order",e.SizeBytes),changeRowCount(!0,t),e.Id}function createButtonGroup(e){const m=document.createElement("div");m.className="btn-toolbar justify-content-end",m.setAttribute("role","toolbar");const t=document.createElement("div");t.className="btn-group me-2",t.setAttribute("role","group");const n=document.createElement("button");n.type="button",n.className="copyurl btn btn-outline-light btn-sm",n.dataset.clipboardText=e.UrlDownload,n.id="url-button-"+e.Id,n.title="Copy URL";const _=document.createElement("i");_.className="bi bi-copy",n.appendChild(_),n.appendChild(document.createTextNode(" URL")),n.addEventListener("click",()=>{showToast(1e3)}),t.appendChild(n);const f=document.createElement("button");f.type="button",f.className="btn btn-outline-light btn-sm dropdown-toggle dropdown-toggle-split",f.setAttribute("data-bs-toggle","dropdown"),f.setAttribute("aria-expanded","false"),t.appendChild(f);const p=document.createElement("ul");p.className="dropdown-menu dropdown-menu-end",p.setAttribute("data-bs-theme","dark");const b=document.createElement("li"),s=document.createElement("a");e.UrlHotlink!==""?(s.className="dropdown-item copyurl",s.title="Copy hotlink",s.style.cursor="pointer",s.setAttribute("data-clipboard-text",e.UrlHotlink),s.onclick=()=>showToast(1e3),s.innerHTML=` Hotlink`):(s.className="dropdown-item",s.innerText="Hotlink not available"),b.appendChild(s),p.appendChild(b),t.appendChild(p);const d=document.createElement("button");d.type="button",d.className="btn btn-outline-light btn-sm",d.title="Share",d.onclick=()=>shareUrl(event,e.Id),d.innerHTML=` +`),t.scrollTop=t.scrollHeight}function setTrafficInfo(e,t){insertReadableSizeTwoOutputs(e,"totalTraffic","totalTrafficUnit"),document.getElementById("cardTraffic").title="Traffic since "+formatUnixTimestamp(t)}function setMemoryUsage(e,t){insertReadableSizeTwoOutputs(t,"totalMemory","memoryUnit");let n=document.getElementById("memoryUnit").innerText;insertReadableSizeForcedUnit(e,"usedMemory",n)}function setDiskUsage(e,t){insertReadableSizeTwoOutputs(t,"totalDisk","diskUnit");let n=document.getElementById("diskUnit").innerText;insertReadableSizeForcedUnit(e,"usedDisk",n)}function formatDuration(e){const t=[{label:"y",value:31536e3},{label:"d",value:86400},{label:"h",value:3600},{label:"m",value:60},{label:"s",value:1}];let n=t.findIndex(t=>e>=t.value);(n===-1||t[n].label==="s")&&(n=t.findIndex(e=>e.label==="m"));const s=t[n],o=t[n+1],i=Math.floor(e/s.value),a=e%s.value,r=Math.floor(a/o.value);return`${i}${s.label} ${r}${o.label}`}function addUptime(){if(currentUptime>3600)return;setTimeout(()=>{++currentUptime,document.getElementById("uptime").innerText=formatDuration(currentUptime),addUptime()},1e3)}function setPercentageBar(e,t,n){let o=t;n!==0[0]&&(o=t/n*100);const s=document.getElementById(e);s.classList.remove("bg-success"),s.classList.remove("bg-warning"),s.classList.remove("bg-danger"),o<70&&s.classList.add("bg-success"),o>=70&&o<90&&s.classList.add("bg-warning"),o>=90&&s.classList.add("bg-danger"),s.style.width=o+"%"}async function loadLogs(e){const t=document.getElementById("logviewer");try{const n=await apiLogGet(e);lastLogUpdate=n.timestamp;let s=!0;if(e!=0){if(n.logEntries=="")return;s=allowScroll(),logContent=logContent+n.logEntries}else logContent=n.logEntries;filterLogs(document.getElementById("logFilter").value),s&&(t.scrollTop=t.scrollHeight)}catch(e){lastLogUpdate=0,console.error("Failed to load logs:",e),t.value="Error loading logs. See console for details."}}async function loadStatus(){try{const e=await apiLogSystemStatus();currentUptime=e.uptime,document.getElementById("labelCpu").innerText=e.cpuLoad+"%",document.getElementById("labelActiveFiles").innerText=e.activeFiles,setPercentageBar("barCpu",e.cpuLoad),setPercentageBar("barDisk",e.diskUsagePercentage),setPercentageBar("barMemory",e.memoryUsagePercentage),setMemoryUsage(e.memoryUsed,e.memoryTotal),setDiskUsage(e.diskUsed,e.diskTotal),setTrafficInfo(e.dataServed,e.trafficRecordingSince)}catch(e){console.error("Failed to server status:",e)}}async function pollInfo(){for(firstStart=!0;!0;)await loadLogs(lastLogUpdate),firstStart?firstStart=!1:await loadStatus(),await new Promise(e=>setTimeout(e,POLL_INTERVAL_S*1e3))}function allowScroll(){const e=document.getElementById("logviewer");return e.scrollTop+e.clientHeight>=e.scrollHeight-5}function deleteLogs(){const n=document.getElementById("deleteLogsSel");if(!n)return;const t=n.value;if(t=="none"||t=="")return;if(!confirm("Do you want to delete the selected logs?")){document.getElementById("deleteLogs").selectedIndex=0;return}let e=Math.floor(Date.now()/1e3);switch(t){case"all":e=0;break;case"2":e=e-2*24*60*60;break;case"7":e=e-7*24*60*60;break;case"14":e=e-14*24*60*60;break;case"30":e=e-30*24*60*60;break;default:return}apiLogsDelete(e).then(e=>{location.reload()}).catch(e=>{alert("Unable to delete logs: "+e),console.error("Error:",e)})}function resetTrafficStat(){if(!confirm("Do you want to reset the traffic statistics?"))return;apiLogResetTraffic().then(e=>{location.reload()}).catch(e=>{alert("Unable to reset stats: "+e),console.error("Error:",e)})}isE2EEnabled=!1,isUploading=!1,rowCount=-1;function initDropzone(){Dropzone.options.uploaddropzone={paramName:"file",dictDefaultMessage:"",createImageThumbnails:!1,chunksUploaded:function(e,t){sendChunkComplete(e,t)},init:function(){dropzoneObject=this,this.on("addedfile",e=>{e.upload.uuid=getUuid(),clampExpiryDaysToMax(),saveUploadDefaults(),addFileProgress(e)}),this.on("queuecomplete",function(){isUploading=!1}),this.on("sending",function(){isUploading=!0}),this.on("error",function(e,t,n){if(console.log(t),n){if(n.status===413){showError(e,"File too large to upload. If you are using a reverse proxy, make sure that the allowed body size is at least 70MB.");return}try{console.log(n),errInfo=JSON.parse(n.responseText),showError(e,"Error: "+errInfo.ErrorMessage)}catch{showError(e,"Error: "+n.responseText)}}else showError(e,"Error: "+t)}),this.on("uploadprogress",function(e,t,n){updateProgressbar(e,t,n)}),isE2EEnabled&&(dropzoneObject.disable(),setE2eUpload())}},document.onpaste=function(e){if(dropzoneObject.disabled)return;const n=document.activeElement;if(n&&(n.hasAttribute("data-allow-regular-paste")||n.hasAttribute("placeholder")))return;var t,s=(e.clipboardData||e.originalEvent.clipboardData).items;for(let e in s)t=s[e],t.kind==="file"&&dropzoneObject.addFile(t.getAsFile()),t.kind==="string"&&t.getAsString(function(e){const t=//gi;if(t.test(e)===!1){let t=new Blob([e],{type:"text/plain"}),n=new File([t],"Pasted Text.txt",{type:"text/plain",lastModified:new Date(0)});dropzoneObject.addFile(n)}})},window.addEventListener("beforeunload",e=>{isUploading&&(e.returnValue="Upload is still in progress. Do you want to close this page?")})}function updateProgressbar(e,t,n){let o=e.upload.uuid,i=document.getElementById(`us-container-${o}`);if(i==null||i.getAttribute("data-complete")==="true")return;let s=Math.round(t);s<0&&(s=0),s>100&&(s=100);let r=Date.now()-i.getAttribute("data-starttime"),c=n/(r/1e3)/1024/1024;document.getElementById(`us-progressbar-${o}`).style.width=s+"%";let a=Math.round(c*10)/10;Number.isNaN(a)||(document.getElementById(`us-progress-info-${o}`).innerText=s+"% - "+a+"MB/s")}function addFileProgress(e){addFileStatus(e.upload.uuid,e.upload.filename)}function setUploadDefaults(){let s=getLocalStorageWithDefault("defaultDownloads",1),o=getLocalStorageWithDefault("defaultExpiry",14),e=getLocalStorageWithDefault("defaultPassword",""),t=getLocalStorageWithDefault("defaultUnlimitedDownloads",!1)==="true",n=getLocalStorageWithDefault("defaultUnlimitedTime",!1)==="true";document.getElementById("allowedDownloads").value=s,document.getElementById("expiryDays").value=o,document.getElementById("password").value=e,document.getElementById("enableDownloadLimit").checked=!t,document.getElementById("enableTimeLimit").checked=!n,e===""?(document.getElementById("enablePassword").checked=!1,document.getElementById("password").disabled=!0):(document.getElementById("enablePassword").checked=!0,document.getElementById("password").disabled=!1),t&&(document.getElementById("allowedDownloads").disabled=!0),n&&(document.getElementById("expiryDays").disabled=!0),maxExpirySeconds>0&&applyMaxExpiryToUpload()}function applyMaxExpiryToUpload(){const n=document.getElementById("enableTimeLimit"),e=document.getElementById("expiryDays"),t=Math.floor(maxExpirySeconds/86400);if(n.checked=!0,n.disabled=!0,t<1){e.value="",e.disabled=!0;return}e.disabled=!1,e.max=t,(e.value===""||Number(e.value)>t)&&(e.value=t),e.addEventListener("input",clampExpiryDaysToMax),e.addEventListener("change",clampExpiryDaysToMax)}function clampExpiryDaysToMax(){const t=Math.floor(maxExpirySeconds/86400),e=document.getElementById("expiryDays");if(t<1||e.value==="")return;Number(e.value)>t?e.value=t:Number(e.value)<1&&(e.value=1)}function saveUploadDefaults(){localStorage.setItem("defaultDownloads",document.getElementById("allowedDownloads").value),localStorage.setItem("defaultExpiry",document.getElementById("expiryDays").value),localStorage.setItem("defaultPassword",document.getElementById("password").value),localStorage.setItem("defaultUnlimitedDownloads",!document.getElementById("enableDownloadLimit").checked),localStorage.setItem("defaultUnlimitedTime",!document.getElementById("enableTimeLimit").checked)}function getLocalStorageWithDefault(e,t){var n=localStorage.getItem(e);return n===null?t:n}function urlencodeFormData(e){let t="";function s(e){return encodeURIComponent(e).replace(/%20/g,"+")}for(var n of e.entries())typeof n[1]=="string"&&(t+=(t?"&":"")+s(n[0])+"="+s(n[1]));return t}function sendChunkComplete(e,t){let c=e.upload.uuid,n=e.name,s=e.size,l=e.size,o=e.type,i=document.getElementById("allowedDownloads").value;clampExpiryDaysToMax();let a=document.getElementById("expiryDays").value,d=document.getElementById("password").value,r=e.isEndToEndEncrypted===!0,u=!0;document.getElementById("enableDownloadLimit").checked||(i=0),document.getElementById("enableTimeLimit").checked||(a=0),r&&(s=e.sizeEncrypted,n="Encrypted File",o=""),apiChunkComplete(c,n,s,l,o,i,a,d,r,u).then(n=>{t();let s=document.getElementById(`us-progress-info-${e.upload.uuid}`);s!=null&&(s.innerText="In Queue...")}).catch(t=>{console.error("Error:",t),dropzoneUploadError(e,t)})}function dropzoneUploadError(e,t){e.accepted=!1,dropzoneObject._errorProcessing([e],t),showError(e,t)}function dropzoneGetFile(e){for(let t=0;t{addRow(n),notifyWorker({type:"fileAdded",item:n});let s=dropzoneGetFile(t);if(s==null)return;s.isEndToEndEncrypted===!0?apiE2eMutexLockUnlock(!1).then(()=>apiE2eGet()).then(n=>{let i=GokapiE2EInfoParse(n);if(i instanceof Error)throw i;let a=GokapiE2EAddFile(t,e,s.name);if(a instanceof Error)throw a;let o=GokapiE2EInfoEncrypt();if(o instanceof Error)throw o;return apiE2eStore(o)}).then(()=>{GokapiE2EDecryptMenu(),removeFileStatus(t)}).catch(e=>{s.accepted=!1,dropzoneObject._errorProcessing([s],e),console.error("Error:",e)}).finally(()=>{apiE2eMutexLockUnlock(!0).catch(e=>{console.error("Failed to release E2E mutex after write: "+e)})}):removeFileStatus(t)}).catch(e=>{let n=dropzoneGetFile(t);n!=null&&dropzoneUploadError(n,e),console.error("Error:",e)})}function parseProgressStatus(e){let n=document.getElementById(`us-container-${e.chunk_id}`);if(n==null)return;n.setAttribute("data-complete","true");let t;switch(e.upload_status){case 0:t="Processing file...";break;case 1:t="Saving file...";break;case 2:t="Finalising...",requestFileInfo(e.file_id,e.chunk_id);break;case 3:t="Error";let n=dropzoneGetFile(e.chunk_id);e.error_message==""&&(e.error_message="Server Error"),n!=null&&dropzoneUploadError(n,e.error_message);return;default:t="Unknown status";break}document.getElementById(`us-progress-info-${e.chunk_id}`).innerText=t}function showError(e,t){let n=e.upload.uuid;document.getElementById(`us-progressbar-${n}`).style.width="100%",document.getElementById(`us-progressbar-${n}`).style.backgroundColor="red",document.getElementById(`us-progress-info-${n}`).innerText=t,document.getElementById(`us-progress-info-${n}`).classList.add("uploaderror")}function editFile(){const e=document.getElementById("mb_save");e.disabled=!0;let s=e.getAttribute("data-fileid"),o=document.getElementById("mi_edit_down").value,i=document.getElementById("mi_edit_expiry").value,t=document.getElementById("mi_edit_pw").value,a=t==="(unchanged)";document.getElementById("mc_download").checked||(o=0),document.getElementById("mc_expiry").checked||(i=0),document.getElementById("mc_password").checked||(a=!1,t="");let r=!1,n="";document.getElementById("mc_replace").checked&&(n=document.getElementById("mi_edit_replace").value,r=n!=""),apiFilesModify(s,o,i,t,a).then(t=>{if(!r){location.reload();return}apiFilesReplace(s,n).then(e=>{location.reload()}).catch(t=>{alert("Unable to edit file: "+t),console.error("Error:",t),e.disabled=!1})}).catch(t=>{alert("Unable to edit file: "+t),console.error("Error:",t),e.disabled=!1})}function showEditModal(e,t,n,s,o,i,a,r,c){let u=$("#modaledit").clone();$("#modaledit").on("hide.bs.modal",function(){$("#modaledit").remove();let e=u.clone();$("body").append(e)});let l=0;maxExpirySeconds>0&&(l=Math.floor(Date.now()/1e3)+maxExpirySeconds,(a||s>l)&&(s=l),a=!1,document.getElementById("mc_expiry").parentElement.classList.add("d-none")),document.getElementById("m_filenamelabel").innerText=e,document.getElementById("mc_expiry").setAttribute("data-timestamp",s),document.getElementById("mb_save").setAttribute("data-fileid",t),createCalendar("mi_edit_expiry",s,l),i?(document.getElementById("mi_edit_down").value="1",document.getElementById("mi_edit_down").disabled=!0,document.getElementById("mc_download").checked=!1):(document.getElementById("mi_edit_down").value=n,document.getElementById("mi_edit_down").disabled=!1,document.getElementById("mc_download").checked=!0),a?(document.getElementById("mi_edit_expiry").value=add14DaysIfBeforeCurrentTime(s),document.getElementById("mi_edit_expiry").disabled=!0,document.getElementById("mc_expiry").checked=!1,calendarInstance._input.disabled=!0):(document.getElementById("mi_edit_expiry").value=s,document.getElementById("mi_edit_expiry").disabled=!1,document.getElementById("mc_expiry").checked=!0,calendarInstance._input.disabled=!1),o?(document.getElementById("mi_edit_pw").value="(unchanged)",document.getElementById("mi_edit_pw").disabled=!1,document.getElementById("mc_password").checked=!0):(document.getElementById("mi_edit_pw").value="",document.getElementById("mi_edit_pw").disabled=!0,document.getElementById("mc_password").checked=!1);let d=document.getElementById("mi_edit_replace");if(c)if(document.getElementById("replaceGroup").style.display="flex",r)document.getElementById("mc_replace").disabled=!0,document.getElementById("mc_replace").title="Replacing content is not available for end-to-end encrypted files",d.add(new Option("Unavailable",0)),d.title="Replacing content is not available for end-to-end encrypted files",d.value="0";else{let e=getAllAvailableFiles();for(let n=0;n{changeRowCount(!1,document.getElementById("row-"+e)),showToastFileDeletion(e),notifyWorker({type:"fileDeleted",id:e})}).catch(e=>{alert("Unable to delete file: "+e),console.error("Error:",e)})}function checkBoxChanged(e,t){let n=!e.checked;n?document.getElementById(t).setAttribute("disabled",""):document.getElementById(t).removeAttribute("disabled"),t==="password"&&n&&(document.getElementById("password").value="")}function parseSseData(e){let t;try{t=JSON.parse(e)}catch(e){console.error("Failed to parse event data:",e);return}switch(t.event){case"download":setNewDownloadCount(t.file_id,t.download_count,t.downloads_remaining);return;case"uploadStatus":parseProgressStatus(t);return;default:console.error("Unknown event",t)}}function setNewDownloadCount(e,t,n){let s=document.getElementById("cell-downloads-"+e);if(s!=null&&(s.innerText=t,s.classList.add("updatedDownloadCount"),setTimeout(()=>s.classList.remove("updatedDownloadCount"),500)),n!=-1){let t=document.getElementById("cell-downloadsRemaining-"+e);t!=null&&(t.innerText=n,t.classList.add("updatedDownloadCount"),setTimeout(()=>t.classList.remove("updatedDownloadCount"),500))}}sseWorkerPort=null;function notifyWorker(e){sseWorkerPort!==null&&sseWorkerPort.postMessage(e)}function registerChangeHandler(){if(typeof SharedWorker!="undefined")try{const e=new SharedWorker("./js/sse-worker.js");e.port.onmessage=e=>{if(e.data.type==="message")parseSseData(e.data.data);else if(e.data.type==="error")console.error("SSE worker connection error:",e.data.detail);else if(e.data.type==="shutdown")setTimeout(function(){window.location.href="./logout_auto"},1e3);else if(e.data.type==="fileAdded")document.getElementById("row-"+sanitizeId(e.data.item.Id))==null&&addRow(e.data.item);else if(e.data.type==="fileDeleted"){let t=document.getElementById("row-"+sanitizeId(e.data.id));t!=null&&changeRowCount(!1,t)}else if(e.data.type==="log"){const{level:t,message:n,detail:s}=e.data;s?console[t](n,s):console[t](n)}},e.onerror=e=>{console.warn("SharedWorker failed, falling back to direct SSE:",e),sseWorkerPort=null,_registerDirectSSE()},e.port.start(),sseWorkerPort=e.port;return}catch(e){console.warn("SharedWorker unavailable, falling back to direct SSE:",e)}_registerDirectSSE()}function _registerDirectSSE(){const e=new EventSource("./uploadStatus");e.onmessage=e=>{parseSseData(e.data)},e.onerror=t=>{t.target.readyState!==EventSource.CLOSED&&e.close(),console.log("Reconnecting to SSE (direct)..."),setTimeout(_registerDirectSSE,5e3)}}statusItemCount=0;function addFileStatus(e,t){const n=document.createElement("div");n.setAttribute("id",`us-container-${e}`),n.classList.add("us-container");const a=document.createElement("div");a.classList.add("filename"),a.textContent=t,n.appendChild(a);const s=document.createElement("div");s.classList.add("upload-progress-container"),s.setAttribute("id",`us-progress-container-${e}`);const r=document.createElement("div");r.classList.add("upload-progress-bar");const o=document.createElement("div");o.setAttribute("id",`us-progressbar-${e}`),o.classList.add("upload-progress-bar-progress"),o.style.width="0%",r.appendChild(o);const i=document.createElement("div");i.setAttribute("id",`us-progress-info-${e}`),i.classList.add("upload-progress-info"),i.textContent="0%",s.appendChild(r),s.appendChild(i),n.appendChild(s),n.setAttribute("data-starttime",Date.now()),n.setAttribute("data-complete","false");const c=document.getElementById("uploadstatus");c.appendChild(n),c.style.visibility="visible",statusItemCount++}function removeFileStatus(e){const t=document.getElementById(`us-container-${e}`);if(t==null)return;t.remove(),statusItemCount--,statusItemCount<1&&(document.getElementById("uploadstatus").style.visibility="hidden")}function addRow(e){let d=document.getElementById("downloadtable"),t=d.insertRow(0);e.Id=sanitizeId(e.Id),t.id="row-"+e.Id;let i=t.insertCell(0),a=t.insertCell(1),s=t.insertCell(2),r=t.insertCell(3),c=t.insertCell(4),o=t.insertCell(5),l=t.insertCell(6);i.innerText=e.Name,i.id="cell-name-"+e.Id,c.id="cell-downloads-"+e.Id,a.innerText=e.Size,e.UnlimitedDownloads?s.innerText="Unlimited":(s.innerText=e.DownloadsRemaining,s.id="cell-downloadsRemaining-"+e.Id),e.UnlimitedTime?r.innerText="Unlimited":r.innerText=formatUnixTimestamp(e.ExpireAt),c.innerText=e.DownloadCount;const n=document.createElement("a");if(n.href=e.UrlDownload,n.target="_blank",n.style.color="inherit",n.id="url-href-"+e.Id,n.textContent=e.Id,o.appendChild(n),e.IsPasswordProtected===!0){const e=document.createElement("i");e.className="bi bi-key",e.title="Password protected",o.appendChild(document.createTextNode(" ")),o.appendChild(e)}return l.appendChild(createButtonGroup(e)),i.classList.add("newItem"),a.classList.add("newItem"),s.classList.add("newItem"),r.classList.add("newItem"),c.classList.add("newItem"),o.classList.add("newItem"),l.classList.add("newItem"),a.setAttribute("data-order",e.SizeBytes),changeRowCount(!0,t),e.Id}function createButtonGroup(e){const m=document.createElement("div");m.className="btn-toolbar justify-content-end",m.setAttribute("role","toolbar");const t=document.createElement("div");t.className="btn-group me-2",t.setAttribute("role","group");const n=document.createElement("button");n.type="button",n.className="copyurl btn btn-outline-light btn-sm",n.dataset.clipboardText=e.UrlDownload,n.id="url-button-"+e.Id,n.title="Copy URL";const _=document.createElement("i");_.className="bi bi-copy",n.appendChild(_),n.appendChild(document.createTextNode(" URL")),n.addEventListener("click",()=>{showToast(1e3)}),t.appendChild(n);const f=document.createElement("button");f.type="button",f.className="btn btn-outline-light btn-sm dropdown-toggle dropdown-toggle-split",f.setAttribute("data-bs-toggle","dropdown"),f.setAttribute("aria-expanded","false"),t.appendChild(f);const p=document.createElement("ul");p.className="dropdown-menu dropdown-menu-end",p.setAttribute("data-bs-theme","dark");const b=document.createElement("li"),s=document.createElement("a");e.UrlHotlink!==""?(s.className="dropdown-item copyurl",s.title="Copy hotlink",s.style.cursor="pointer",s.setAttribute("data-clipboard-text",e.UrlHotlink),s.onclick=()=>showToast(1e3),s.innerHTML=` Hotlink`):(s.className="dropdown-item",s.innerText="Hotlink not available"),b.appendChild(s),p.appendChild(b),t.appendChild(p);const d=document.createElement("button");d.type="button",d.className="btn btn-outline-light btn-sm",d.title="Share",d.onclick=()=>shareUrl(event,e.Id),d.innerHTML=` `,t.appendChild(d);const u=document.createElement("button");u.type="button",u.className="btn btn-outline-light btn-sm dropdown-toggle dropdown-toggle-split",u.setAttribute("data-bs-toggle","dropdown"),u.setAttribute("aria-expanded","false"),u.id=`shareDropdown-${e.Id}`,t.appendChild(u);const h=document.createElement("ul");h.className="dropdown-menu dropdown-menu-end",h.setAttribute("data-bs-theme","dark");const g=document.createElement("li"),o=document.createElement("a");o.className="dropdown-item",o.id=`qrcode-${e.Id}`,o.style.cursor="pointer",o.title="Open QR Code",o.onclick=()=>showQrCode(e.UrlDownload),o.innerHTML=` QR Code`,g.appendChild(o),h.appendChild(g);const v=document.createElement("li"),r=document.createElement("a");r.className="dropdown-item",r.title="Share via email",r.id=`email-${e.Id}`,r.target="_blank",r.href=`mailto:?body=${encodeURIComponent(e.UrlDownload)}`,r.innerHTML=` Email`,v.appendChild(r),h.appendChild(v),t.appendChild(h);const l=document.createElement("div");l.className="btn-group",l.setAttribute("role","group");const a=document.createElement("button");a.type="button",a.className="btn btn-outline-light btn-sm",a.title="Download",e.RequiresClientSideDecryption&&a.classList.add("disabled");const j=document.createElement("i");j.className="bi bi-download",a.appendChild(j),a.addEventListener("click",()=>{downloadFileWithPresign(e.Id)}),l.appendChild(a);const c=document.createElement("button");c.type="button",c.className="btn btn-outline-light btn-sm",c.title="Edit";const y=document.createElement("i");y.className="bi bi-pencil",c.appendChild(y),c.addEventListener("click",()=>{showEditModal(e.Name,e.Id,e.DownloadsRemaining,e.ExpireAt,e.IsPasswordProtected,e.UnlimitedDownloads,e.UnlimitedTime,e.IsEndToEndEncrypted,canReplaceOwnFiles)}),l.appendChild(c);const i=document.createElement("button");i.type="button",i.className="btn btn-outline-danger btn-sm",i.title="Delete",i.id="button-delete-"+e.Id;const w=document.createElement("i");return w.className="bi bi-trash3",i.appendChild(w),i.addEventListener("click",()=>{deleteFile(e.Id)}),l.appendChild(i),m.appendChild(t),m.appendChild(l),m}function sanitizeId(e){return e.replace(/[^a-zA-Z0-9]/g,"")}function changeRowCount(e,t){let n=$("#maintable").DataTable();rowCount==-1&&(rowCount=n.rows().count()),e?(++rowCount,n.row.add(t)):(--rowCount,t.classList.add("rowDeleting"),setTimeout(()=>{n.row(t).remove(),t.remove()},290));let s=document.getElementsByClassName("dataTables_empty")[0];typeof s!="undefined"?s.innerText="Files stored: "+rowCount:document.getElementsByClassName("dataTables_info")[0].innerText="Files stored: "+rowCount}function hideQrCode(){document.getElementById("qroverlay").style.display="none",document.getElementById("qrcode").innerHTML=""}function showQrCode(e){const t=document.getElementById("qroverlay");t.style.display="block",new QRCode(document.getElementById("qrcode"),{text:e,width:200,height:200,colorDark:"#000000",colorLight:"#ffffff",correctLevel:QRCode.CorrectLevel.H}),t.addEventListener("click",hideQrCode)}function showToastFileDeletion(e){let t=document.getElementById("toastnotificationUndo"),n=document.getElementById("cell-name-"+e).innerText,s=document.getElementById("toastFilename"),o=document.getElementById("toastUndoButton");s.innerText=n,o.dataset.fileid=e,hideToast(),t.classList.add("show"),clearTimeout(toastId),toastId=setTimeout(()=>{hideFileToast()},5e3)}function hideFileToast(){document.getElementById("toastnotificationUndo").classList.remove("show")}function handleUndo(e){hideFileToast(),apiFilesRestore(e.dataset.fileid).then(e=>{addRow(e.FileInfo),notifyWorker({type:"fileAdded",item:e.FileInfo}),isE2EEnabled&&GokapiE2EDecryptMenu()}).catch(e=>{alert("Unable to restore file: "+e),console.error("Error:",e)})}function shareUrl(e,t){if(!navigator.share){e.stopPropagation(),bootstrap.Dropdown.getOrCreateInstance(document.getElementById(`shareDropdown-${t}`)).toggle();return}let n=document.getElementById("cell-name-"+t).innerText,s=document.getElementById("url-href-"+t).getAttribute("href");navigator.share({title:n,url:s})}function showDeprecationNotice(){let e=document.getElementById("toastDeprecation");e.classList.add("show"),setTimeout(()=>{e.classList.remove("show")},5e3)}function changeUserPermission(e,t,n){let s=document.getElementById(n);if(s.classList.contains("perm-processing")||s.classList.contains("perm-nochange"))return;let o=s.classList.contains("perm-granted");s.classList.add("perm-processing"),s.classList.remove("perm-granted"),s.classList.remove("perm-notgranted");let i="GRANT";o&&(i="REVOKE"),t=="PERM_REPLACE_OTHER"&&!o&&(hasNotPermissionReplace=document.getElementById("perm_replace_"+e).classList.contains("perm-notgranted"),hasNotPermissionReplace&&(showToast(2e3,"Also granting permission to replace own files"),changeUserPermission(e,"PERM_REPLACE","perm_replace_"+e))),t=="PERM_REPLACE"&&o&&(hasPermissionReplaceOthers=document.getElementById("perm_replace_other_"+e).classList.contains("perm-granted"),hasPermissionReplaceOthers&&(showToast(2e3,"Also revoking permission to replace files of other users"),changeUserPermission(e,"PERM_REPLACE_OTHER","perm_replace_other_"+e))),apiUserModify(e,t,i).then(e=>{o?s.classList.add("perm-notgranted"):s.classList.add("perm-granted"),s.classList.remove("perm-processing")}).catch(e=>{o?s.classList.add("perm-granted"):s.classList.add("perm-notgranted"),s.classList.remove("perm-processing"),alert("Unable to set permission: "+e),console.error("Error:",e)})}function changeRank(e,t,n){let s=document.getElementById(n);if(s.disabled)return;s.disabled=!0,apiUserChangeRank(e,t).then(e=>{location.reload()}).catch(e=>{s.disabled=!1,alert("Unable to change rank: "+e),console.error("Error:",e)})}function showDeleteUserModal(e,t){let n=document.getElementById("checkboxDelete");n.checked=!1,document.getElementById("deleteModalBody").innerText=t,$("#deleteModal").modal("show"),document.getElementById("buttonDelete").onclick=function(){apiUserDelete(e,n.checked).then(t=>{$("#deleteModal").modal("hide"),document.getElementById("row-"+e).classList.add("rowDeleting"),setTimeout(()=>{document.getElementById("row-"+e).remove()},290)}).catch(e=>{alert("Unable to delete user: "+e),console.error("Error:",e)})}}function showAddUserModal(){let e=$("#newUserModal").clone();$("#newUserModal").on("hide.bs.modal",function(){$("#newUserModal").remove();let t=e.clone();$("body").append(t)}),$("#newUserModal").modal("show")}function showResetPwModal(e,t){let n=$("#resetPasswordModal").clone();$("#resetPasswordModal").on("hide.bs.modal",function(){$("#resetPasswordModal").remove();let e=n.clone();$("body").append(e)}),document.getElementById("l_userpwreset").innerText=t;let s=document.getElementById("resetPasswordButton");s.onclick=function(){resetPw(e,document.getElementById("generateRandomPassword").checked)},$("#resetPasswordModal").modal("show")}function resetPw(e,t){let n=document.getElementById("resetPasswordButton");document.getElementById("resetPasswordButton").disabled=!0,apiUserResetPassword(e,t).then(e=>{if(!t){$("#resetPasswordModal").modal("hide"),showToast(1e3,"Password change requirement set successfully");return}n.style.display="none",document.getElementById("cancelPasswordButton").style.display="none",document.getElementById("formentryReset").style.display="none",document.getElementById("randomPasswordContainer").style.display="block",document.getElementById("closeModalResetPw").style.display="block",document.getElementById("l_returnedPw").innerText=e.password,document.getElementById("copypwclip").onclick=function(){navigator.clipboard.writeText(e.password),showToast(1e3,"Password copied to clipboard")}}).catch(e=>{alert("Unable to reset user password: "+e),console.error("Error:",e),n.disabled=!1})}function addNewUser(){let e=document.getElementById("mb_addUser");e.disabled=!0;let t=document.getElementById("newUserForm");if(t.checkValidity()){let t=document.getElementById("e_userName");apiUserCreate(t.value.trim()).then(e=>{$("#newUserModal").modal("hide"),addRowUser(e.id,e.name,e.permissions),console.log(e)}).catch(t=>{t.message=="duplicate"?(alert("A user already exists with that name"),e.disabled=!1):(alert("Unable to create user: "+t),console.error("Error:",t),e.disabled=!1)})}else t.classList.add("was-validated"),e.disabled=!1}const PermissionDefinitions=[{key:"UserPermGuestUploads",bit:1<<8,icon:"bi bi-box-arrow-in-down",title:"Create file requests",htmlId:e=>`perm_guest_upload_${e}`,apiName:"PERM_GUEST_UPLOAD",disabled:!1},{key:"UserPermReplaceUploads",bit:1<<0,icon:"bi bi-recycle",title:"Replace own uploads",htmlId:e=>`perm_replace_${e}`,apiName:"PERM_REPLACE",disabled:!1},{key:"UserPermListOtherUploads",bit:1<<1,icon:"bi bi-eye",title:"List other uploads",htmlId:e=>`perm_list_${e}`,apiName:"PERM_LIST",disabled:!1},{key:"UserPermEditOtherUploads",bit:1<<2,icon:"bi bi-pencil",title:"Edit other uploads",htmlId:e=>`perm_edit_${e}`,apiName:"PERM_EDIT",disabled:!1},{key:"UserPermDeleteOtherUploads",bit:1<<4,icon:"bi bi-trash3",title:"Delete other uploads",htmlId:e=>`perm_delete_${e}`,apiName:"PERM_DELETE",disabled:!1},{key:"UserPermReplaceOtherUploads",bit:1<<3,icon:"bi bi-arrow-left-right",title:"Replace other uploads",htmlId:e=>`perm_replace_other_${e}`,apiName:"PERM_REPLACE_OTHER",disabled:!1},{key:"UserPermManageLogs",bit:1<<5,icon:"bi bi-card-list",title:"Manage system logs",htmlId:e=>`perm_logs_${e}`,apiName:"PERM_LOGS",disabled:!1},{key:"UserPermManageUsers",bit:1<<7,icon:"bi bi-people",title:"Manage users",htmlId:e=>`perm_users_${e}`,apiName:"PERM_USERS",disabled:!0},{key:"UserPermManageApiKeys",bit:1<<6,icon:"bi bi-sliders2",title:"Manage all API keys",htmlId:e=>`perm_api_${e}`,apiName:"PERM_API",disabled:!1}];function hasPermission(e,t){return(e&t)!==0}function addRowUser(e,t,n){e=sanitizeUserId(e);let m=document.getElementById("usertable"),o=m.insertRow(1);o.id="row-"+e;let c=o.insertCell(0),l=o.insertCell(1),d=o.insertCell(2),u=o.insertCell(3),h=o.insertCell(4),r=o.insertCell(5);c.classList.add("newUser"),l.classList.add("newUser"),d.classList.add("newUser"),u.classList.add("newUser"),h.classList.add("newUser"),r.classList.add("newUser"),c.innerText=t,l.innerText="User",d.innerText="Never",u.innerText="0";const a=document.createElement("div");if(a.className="btn-group",a.setAttribute("role","group"),isInternalAuth){const n=document.createElement("button");n.id=`pwchange-${e}`,n.type="button",n.className="btn btn-outline-light btn-sm",n.title="Reset Password",n.onclick=()=>showResetPwModal(e,t),n.innerHTML=``,a.appendChild(n)}const s=document.createElement("button");s.id=`changeRank_${e}`,s.type="button",s.className="btn btn-outline-light btn-sm",s.title="Promote User",isAdmin?s.onclick=()=>changeRank(e,"ADMIN",`changeRank_${e}`):s.disabled=!0,s.innerHTML=``,a.appendChild(s);const i=document.createElement("button");i.id=`delete-${e}`,i.type="button",i.className="btn btn-outline-danger btn-sm",i.title="Delete",i.onclick=()=>showDeleteUserModal(e,t),i.innerHTML=``,a.appendChild(i),r.innerHTML="",r.appendChild(a),h.innerHTML=PermissionDefinitions.map(t=>{let s="perm-notgranted";hasPermission(n,t.bit)&&(s="perm-granted");const o=t.htmlId(e);let i="";return(!hasPermission(userPermissions,t.bit)||t.disabled)&&(i="perm-nochange"),` diff --git a/openapi.json b/openapi.json index 49f69889..f705f60f 100644 --- a/openapi.json +++ b/openapi.json @@ -496,7 +496,7 @@ { "name": "expiryDays", "in": "header", - "description": "How many days the file will be stored. Default of 14 will be used if empty. Unlimited if 0 is passed.", + "description": "How many days the file will be stored. Default of 14 will be used if empty. Unlimited if 0 is passed. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), values above it and unlimited are refused and the default is reduced to the maximum.", "required": false, "schema": { "type": "integer" @@ -1026,7 +1026,7 @@ "name": "expiryDays", "in": "header", "required": false, - "description": "How many days the file will be stored. Original value from web interface will be used if empty. Unlimited if 0 is passed.", + "description": "How many days the file will be stored. Original value from web interface will be used if empty. Unlimited if 0 is passed. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), values above it and unlimited are refused, and an empty value is refused if the original value exceeds the maximum.", "schema": { "type": "integer" } @@ -1181,7 +1181,7 @@ "schema": { "type": "integer" }, - "description": "Unix timestamp of the file expiration date. Unlimited if 0 is passed." + "description": "Unix timestamp of the file expiration date. Unlimited if 0 is passed. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), values above it and unlimited are refused." }, { "name": "password", @@ -1756,7 +1756,7 @@ { "name": "expiry", "in": "header", - "description": "The expiry as a UTC unix timestamp. No expiry if 0", + "description": "The expiry as a UTC unix timestamp. No expiry if 0. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), unlimited and values above it are refused, and a new request without an expiry expires after 14 days or the maximum, whichever is shorter.", "required": false, "style": "simple", "explode": false, @@ -2590,6 +2590,11 @@ "MaxChunksize": { "type": "integer", "example": 40 + }, + "MaxExpirySeconds": { + "type": "integer", + "description": "The maximum time in seconds that a file can be stored before it expires (GOKAPI_MAX_EXPIRY_SECONDS). 0 if there is no limit", + "example": 0 } }, "description": "ConfigInfo is the struct used for returning configuration data" @@ -2627,7 +2632,7 @@ }, "expiryDays": { "type": "integer", - "description": "How many days the file will be stored. Default of 14 will be used if empty. Unlimited if 0 is passed." + "description": "How many days the file will be stored. Default of 14 will be used if empty. Unlimited if 0 is passed. If the server sets a maximum expiry (GOKAPI_MAX_EXPIRY_SECONDS), values above it and unlimited are refused and the default is reduced to the maximum." }, "password": { "type": "string",