Skip to content

Commit 1969d43

Browse files
committed
Fixed JS function being overwritten in last commit, added DB cache, fixed tests
1 parent 4eaab13 commit 1969d43

File tree

11 files changed

+64
-29
lines changed

11 files changed

+64
-29
lines changed

cmd/gokapi/Main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ import (
3434

3535
// versionGokapi is the current version in readable form.
3636
// Other version numbers can be modified in /build/go-generate/updateVersionNumbers.go
37-
const versionGokapi = "2.0.0-beta2"
37+
const versionGokapi = "2.0.0"
3838

3939
// The following calls update the version numbers, update documentation, minify Js/CSS and build the WASM modules
4040
//go:generate go run "../../build/go-generate/updateVersionNumbers.go"

internal/configuration/database/Database.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"errors"
55
"fmt"
66
"github.com/forceu/gokapi/internal/configuration/database/dbabstraction"
7+
"github.com/forceu/gokapi/internal/configuration/database/dbcache"
78
"github.com/forceu/gokapi/internal/helper"
89
"github.com/forceu/gokapi/internal/models"
910
"net/url"
@@ -15,6 +16,7 @@ var db dbabstraction.Database
1516
// Connect establishes a connection to the database and creates the table structure, if necessary
1617
func Connect(config models.DbConnection) {
1718
var err error
19+
dbcache.Init()
1820
db, err = dbabstraction.GetNew(config)
1921
if err != nil {
2022
panic(err)
@@ -270,7 +272,10 @@ func SaveUser(user models.User, isNewUser bool) {
270272

271273
// UpdateUserLastOnline writes the last online time to the database
272274
func UpdateUserLastOnline(id int) {
273-
db.UpdateUserLastOnline(id)
275+
// To reduce database writes, the entry is only updated if the last timestamp is more than 30 seconds old
276+
if dbcache.LastOnlineRequiresSave(id) {
277+
db.UpdateUserLastOnline(id)
278+
}
274279
}
275280

276281
// DeleteUser deletes a user with the given ID

internal/configuration/database/Database_test.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package database
33
import (
44
"github.com/alicebob/miniredis/v2"
55
"github.com/forceu/gokapi/internal/configuration/database/dbabstraction"
6+
"github.com/forceu/gokapi/internal/configuration/database/dbcache"
67
"github.com/forceu/gokapi/internal/models"
78
"github.com/forceu/gokapi/internal/test"
89
"log"
@@ -306,7 +307,10 @@ func TestUsers(t *testing.T) {
306307
return len(GetAllUsers())
307308
}, 2)
308309
test.IsEqual(t, allUsersSqlite, allUsersRedis)
309-
runAllTypesNoOutput(t, func() { UpdateUserLastOnline(1) })
310+
runAllTypesNoOutput(t, func() {
311+
dbcache.Init()
312+
UpdateUserLastOnline(1)
313+
})
310314
runAllTypesCompareTwoOutputs(t, func() (any, any) {
311315
retrievedUser, ok := GetUser(1)
312316
isUpdated := time.Now().Unix()-retrievedUser.LastOnline < 5 && time.Now().Unix()-retrievedUser.LastOnline > -1
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package dbcache
2+
3+
import (
4+
"sync"
5+
"time"
6+
)
7+
8+
var lastOnlineTimeUpdate map[int]int64
9+
var lastOnlineTimeMutex sync.Mutex
10+
11+
// Init starts the DB Cache
12+
func Init() {
13+
lastOnlineTimeUpdate = make(map[int]int64)
14+
}
15+
16+
// LastOnlineRequiresSave returns true if the last update time of the user is older than 60 seconds.
17+
func LastOnlineRequiresSave(userId int) bool {
18+
lastOnlineTimeMutex.Lock()
19+
timestamp := time.Now().Unix()
20+
defer lastOnlineTimeMutex.Unlock()
21+
if lastOnlineTimeUpdate[userId] < (timestamp - 60) {
22+
lastOnlineTimeUpdate[userId] = timestamp
23+
return true
24+
}
25+
return false
26+
}

internal/configuration/database/provider/sqlite/Sqlite.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,8 +164,8 @@ func (p DatabaseProvider) init(dbConfig models.DbConnection) (DatabaseProvider,
164164
if err != nil {
165165
return DatabaseProvider{}, err
166166
}
167-
p.sqliteDb.SetMaxOpenConns(10000)
168-
p.sqliteDb.SetMaxIdleConns(10000)
167+
p.sqliteDb.SetMaxOpenConns(5)
168+
p.sqliteDb.SetMaxIdleConns(5)
169169

170170
if !helper.FileExists(dbConfig.HostUrl) {
171171
return p, p.createNewDatabase()

internal/configuration/database/provider/sqlite/users.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,7 @@ func (p DatabaseProvider) SaveUser(user models.User, isNewUser bool) {
9898
// UpdateUserLastOnline writes the last online time to the database
9999
func (p DatabaseProvider) UpdateUserLastOnline(id int) {
100100
timeNow := time.Now().Unix()
101-
// To reduce database writes, the entry is only updated, if the last timestamp is more than 30 seconds old
102-
_, err := p.sqliteDb.Exec("UPDATE Users SET LastOnline= ? WHERE Id = ? AND (? - LastOnline > 30)", timeNow, id, timeNow)
101+
_, err := p.sqliteDb.Exec("UPDATE Users SET LastOnline= ? WHERE Id = ?", timeNow, id, timeNow)
103102
helper.Check(err)
104103
}
105104

internal/test/testconfiguration/TestConfiguration.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ func Create(initFiles bool) {
7070
os.WriteFile(dataDir+"/c4f9375f9834b4e7f0a528cc65c055702bf5f24a", []byte("456"), 0777)
7171
os.WriteFile(dataDir+"/e017693e4a04a59d0b0f400fe98177fe7ee13cf7", []byte("789"), 0777)
7272
os.WriteFile(dataDir+"/2341354656543213246465465465432456898794", []byte("abc"), 0777)
73+
os.WriteFile(dataDir+"/03cfd743661f07975fa2f1220c5194cbaff48451", []byte("def"), 0777)
74+
os.WriteFile(dataDir+"/pendingdeletion", []byte("ghi"), 0777)
7375
os.WriteFile(dataDir+"/unlimitedtest", []byte("def"), 0777)
7476
os.WriteFile(baseDir+"/fileupload.jpg", []byte("abc"), 0777)
7577
}

internal/webserver/api/Api_test.go

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,23 +1118,23 @@ func TestDeleteFile(t *testing.T) {
11181118
database.SaveMetaData(models.File{
11191119
Id: "smalltestfile1",
11201120
Name: "smalltestfile1",
1121-
SHA1: "smalltestfile1",
1121+
SHA1: "03cfd743661f07975fa2f1220c5194cbaff48451",
11221122
ExpireAt: 2147483646,
11231123
DownloadsRemaining: 1,
11241124
UserId: idUser,
11251125
})
11261126
database.SaveMetaData(models.File{
11271127
Id: "smalltestfile2",
11281128
Name: "smalltestfile2",
1129-
SHA1: "smalltestfile2",
1129+
SHA1: "03cfd743661f07975fa2f1220c5194cbaff48451",
11301130
ExpireAt: 2147483646,
11311131
DownloadsRemaining: 1,
11321132
UserId: idSuperAdmin,
11331133
})
11341134
database.SaveMetaData(models.File{
11351135
Id: "smalltestfileDelay",
11361136
Name: "smalltestfileDelay",
1137-
SHA1: "2341354656543213246465465465432456898794",
1137+
SHA1: "03cfd743661f07975fa2f1220c5194cbaff48451",
11381138
ExpireAt: 2147483646,
11391139
DownloadsRemaining: 1,
11401140
UserId: idUser,
@@ -1199,47 +1199,47 @@ func testDeleteFileCall(t *testing.T, apiKey, fileId, delay string, resultCode i
11991199
func TestRestoreFile(t *testing.T) {
12001200
config := configuration.Get()
12011201
fileUser := models.File{
1202-
Id: "smalltestfile1",
1203-
Name: "smalltestfile1",
1204-
SHA1: "e017693e4a04a59d0b0f400fe98177fe7ee13cf7",
1202+
Id: "pendingdeletion1",
1203+
Name: "pendingdeletion1",
1204+
SHA1: "pendingdeletion",
12051205
ExpireAt: 2147483646,
12061206
DownloadsRemaining: 1,
12071207
UserId: idUser,
12081208
}
12091209
fileAdmin := models.File{
1210-
Id: "smalltestfile2",
1211-
Name: "smalltestfile2",
1212-
SHA1: "2341354656543213246465465465432456898794",
1210+
Id: "pendingdeletion2",
1211+
Name: "pendingdeletion2",
1212+
SHA1: "pendingdeletion",
12131213
ExpireAt: 2147483646,
12141214
DownloadsRemaining: 1,
12151215
UserId: idSuperAdmin,
12161216
}
12171217
database.SaveMetaData(fileUser)
12181218
database.SaveMetaData(fileAdmin)
1219-
_, ok := database.GetMetaDataById("smalltestfile1")
1219+
_, ok := database.GetMetaDataById(fileUser.Id)
12201220
test.IsEqualBool(t, ok, true)
1221-
_, ok = database.GetMetaDataById("smalltestfile2")
1221+
_, ok = database.GetMetaDataById(fileAdmin.Id)
12221222
test.IsEqualBool(t, ok, true)
12231223

12241224
apiKey := testAuthorisation(t, "/files/restore", models.ApiPermDelete)
12251225
testRestoreFileCall(t, apiKey.Id, "", 400, `{"Result":"error","ErrorMessage":"header id is required"}`)
12261226
testRestoreFileCall(t, apiKey.Id, "invalid", 404, `{"Result":"error","ErrorMessage":"Invalid file ID provided or file has already been deleted."}`)
1227-
testRestoreFileCall(t, apiKey.Id, "smalltestfile1", 200, fileUser.ToJsonResult(config.ServerUrl, config.IncludeFilename))
1228-
testRestoreFileCall(t, apiKey.Id, "smalltestfile2", 401, `{"Result":"error","ErrorMessage":"No permission to restore this file"}`)
1227+
testRestoreFileCall(t, apiKey.Id, fileUser.Id, 200, fileUser.ToJsonResult(config.ServerUrl, config.IncludeFilename))
1228+
testRestoreFileCall(t, apiKey.Id, fileAdmin.Id, 401, `{"Result":"error","ErrorMessage":"No permission to restore this file"}`)
12291229

12301230
storage.DeleteFileSchedule(fileUser.Id, 1, true)
12311231
storage.DeleteFileSchedule(fileAdmin.Id, 1, true)
12321232

1233-
time.Sleep(500 * time.Millisecond)
1233+
time.Sleep(400 * time.Millisecond)
12341234
file, ok := database.GetMetaDataById(fileUser.Id)
12351235
test.IsEqualBool(t, ok, true)
12361236
test.IsEqualBool(t, file.PendingDeletion != 0, true)
12371237
file, ok = database.GetMetaDataById(fileAdmin.Id)
12381238
test.IsEqualBool(t, ok, true)
12391239
test.IsEqualBool(t, file.PendingDeletion != 0, true)
12401240

1241-
testRestoreFileCall(t, apiKey.Id, "smalltestfile1", 200, fileUser.ToJsonResult(config.ServerUrl, config.IncludeFilename))
1242-
testRestoreFileCall(t, apiKey.Id, "smalltestfile2", 401, `{"Result":"error","ErrorMessage":"No permission to restore this file"}`)
1241+
testRestoreFileCall(t, apiKey.Id, fileUser.Id, 200, fileUser.ToJsonResult(config.ServerUrl, config.IncludeFilename))
1242+
testRestoreFileCall(t, apiKey.Id, fileAdmin.Id, 401, `{"Result":"error","ErrorMessage":"No permission to restore this file"}`)
12431243

12441244
file, ok = database.GetMetaDataById(fileUser.Id)
12451245
test.IsEqualBool(t, ok, true)
@@ -1249,7 +1249,6 @@ func TestRestoreFile(t *testing.T) {
12491249
test.IsEqualBool(t, file.PendingDeletion != 0, true)
12501250

12511251
time.Sleep(600 * time.Millisecond)
1252-
12531252
file, ok = database.GetMetaDataById(fileUser.Id)
12541253
test.IsEqualBool(t, ok, true)
12551254
test.IsEqualInt64(t, file.PendingDeletion, 0)

internal/webserver/web/static/js/admin_ui_users.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ function addNewUser() {
193193

194194
function addRowUser(userid, name) {
195195

196-
userid = sanitizeId(userid);
196+
userid = sanitizeUserId(userid);
197197

198198
let table = document.getElementById("usertable");
199199
let row = table.insertRow(1);
@@ -289,7 +289,7 @@ function addRowUser(userid, name) {
289289
}, 700);
290290
}
291291

292-
function sanitizeId(id) {
292+
function sanitizeUserId(id) {
293293
const numericId = id.toString().trim();
294294
if (!/^\d+$/.test(numericId)) {
295295
throw new Error("Invalid ID: must contain only digits.");

0 commit comments

Comments
 (0)