Delete services
Browse files- services/auth.service.go +0 -347
- services/file.service.go +0 -582
- services/upload.service.go +0 -167
- services/user.service.go +0 -91
services/auth.service.go
DELETED
|
@@ -1,347 +0,0 @@
|
|
| 1 |
-
package services
|
| 2 |
-
|
| 3 |
-
import (
|
| 4 |
-
"bytes"
|
| 5 |
-
"context"
|
| 6 |
-
"encoding/base64"
|
| 7 |
-
"encoding/binary"
|
| 8 |
-
"encoding/json"
|
| 9 |
-
"errors"
|
| 10 |
-
"fmt"
|
| 11 |
-
"log"
|
| 12 |
-
"math/big"
|
| 13 |
-
"net"
|
| 14 |
-
"net/http"
|
| 15 |
-
"strconv"
|
| 16 |
-
"time"
|
| 17 |
-
|
| 18 |
-
"github.com/divyam234/teldrive/models"
|
| 19 |
-
"github.com/divyam234/teldrive/schemas"
|
| 20 |
-
"github.com/divyam234/teldrive/types"
|
| 21 |
-
"github.com/divyam234/teldrive/utils"
|
| 22 |
-
"github.com/divyam234/teldrive/utils/auth"
|
| 23 |
-
"github.com/gin-gonic/gin"
|
| 24 |
-
"github.com/go-jose/go-jose/v3/jwt"
|
| 25 |
-
"github.com/gorilla/websocket"
|
| 26 |
-
"github.com/gotd/td/session"
|
| 27 |
-
tgauth "github.com/gotd/td/telegram/auth"
|
| 28 |
-
"github.com/gotd/td/telegram/auth/qrlogin"
|
| 29 |
-
"github.com/gotd/td/tg"
|
| 30 |
-
"github.com/gotd/td/tgerr"
|
| 31 |
-
"gorm.io/gorm"
|
| 32 |
-
)
|
| 33 |
-
|
| 34 |
-
type AuthService struct {
|
| 35 |
-
Db *gorm.DB
|
| 36 |
-
SessionMaxAge int
|
| 37 |
-
SessionCookieName string
|
| 38 |
-
}
|
| 39 |
-
|
| 40 |
-
type SessionData struct {
|
| 41 |
-
Version int
|
| 42 |
-
Data session.Data
|
| 43 |
-
}
|
| 44 |
-
type SocketMessage struct {
|
| 45 |
-
AuthType string `json:"authType"`
|
| 46 |
-
Message string `json:"message"`
|
| 47 |
-
PhoneNo string `json:"phoneNo,omitempty"`
|
| 48 |
-
PhoneCodeHash string `json:"phoneCodeHash,omitempty"`
|
| 49 |
-
PhoneCode string `json:"phoneCode,omitempty"`
|
| 50 |
-
Password string `json:"password,omitempty"`
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
func IP4toInt(IPv4Address net.IP) int64 {
|
| 54 |
-
IPv4Int := big.NewInt(0)
|
| 55 |
-
IPv4Int.SetBytes(IPv4Address.To4())
|
| 56 |
-
return IPv4Int.Int64()
|
| 57 |
-
}
|
| 58 |
-
|
| 59 |
-
func Pack32BinaryIP4(ip4Address string) []byte {
|
| 60 |
-
ipv4Decimal := IP4toInt(net.ParseIP(ip4Address))
|
| 61 |
-
|
| 62 |
-
buf := new(bytes.Buffer)
|
| 63 |
-
binary.Write(buf, binary.BigEndian, uint32(ipv4Decimal))
|
| 64 |
-
return buf.Bytes()
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
func generateTgSession(dcID int, authKey []byte, port int) string {
|
| 68 |
-
|
| 69 |
-
dcMaps := map[int]string{
|
| 70 |
-
1: "149.154.175.53",
|
| 71 |
-
2: "149.154.167.51",
|
| 72 |
-
3: "149.154.175.100",
|
| 73 |
-
4: "149.154.167.91",
|
| 74 |
-
5: "91.108.56.130",
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
dcIDByte := byte(dcID)
|
| 78 |
-
serverAddressBytes := Pack32BinaryIP4(dcMaps[dcID])
|
| 79 |
-
portByte := make([]byte, 2)
|
| 80 |
-
binary.BigEndian.PutUint16(portByte, uint16(port))
|
| 81 |
-
|
| 82 |
-
packet := make([]byte, 0)
|
| 83 |
-
packet = append(packet, dcIDByte)
|
| 84 |
-
packet = append(packet, serverAddressBytes...)
|
| 85 |
-
packet = append(packet, portByte...)
|
| 86 |
-
packet = append(packet, authKey...)
|
| 87 |
-
|
| 88 |
-
base64Encoded := base64.URLEncoding.EncodeToString(packet)
|
| 89 |
-
return "1" + base64Encoded
|
| 90 |
-
}
|
| 91 |
-
|
| 92 |
-
func setCookie(c *gin.Context, key string, value string, age int) {
|
| 93 |
-
|
| 94 |
-
config := utils.GetConfig()
|
| 95 |
-
|
| 96 |
-
if config.CookieSameSite {
|
| 97 |
-
c.SetSameSite(2)
|
| 98 |
-
} else {
|
| 99 |
-
c.SetSameSite(4)
|
| 100 |
-
}
|
| 101 |
-
c.SetCookie(key, value, age, "/", c.Request.Host, config.Https, true)
|
| 102 |
-
|
| 103 |
-
}
|
| 104 |
-
|
| 105 |
-
func (as *AuthService) LogIn(c *gin.Context) (*schemas.Message, *types.AppError) {
|
| 106 |
-
var session types.TgSession
|
| 107 |
-
if err := c.ShouldBindJSON(&session); err != nil {
|
| 108 |
-
return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest}
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
now := time.Now().UTC()
|
| 112 |
-
|
| 113 |
-
jwtClaims := &types.JWTClaims{Claims: jwt.Claims{
|
| 114 |
-
Subject: strconv.FormatInt(session.UserID, 10),
|
| 115 |
-
IssuedAt: jwt.NewNumericDate(now),
|
| 116 |
-
Expiry: jwt.NewNumericDate(now.Add(time.Duration(as.SessionMaxAge) * time.Second)),
|
| 117 |
-
}, TgSession: session.Sesssion,
|
| 118 |
-
Name: session.Name,
|
| 119 |
-
UserName: session.UserName,
|
| 120 |
-
Bot: session.Bot,
|
| 121 |
-
IsPremium: session.IsPremium,
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
jweToken, err := auth.Encode(jwtClaims)
|
| 125 |
-
|
| 126 |
-
if err != nil {
|
| 127 |
-
return nil, &types.AppError{Error: err, Code: http.StatusBadRequest}
|
| 128 |
-
}
|
| 129 |
-
|
| 130 |
-
user := models.User{
|
| 131 |
-
UserId: session.UserID,
|
| 132 |
-
Name: session.Name,
|
| 133 |
-
UserName: session.UserName,
|
| 134 |
-
IsPremium: session.IsPremium,
|
| 135 |
-
TgSession: session.Sesssion,
|
| 136 |
-
}
|
| 137 |
-
|
| 138 |
-
var result []models.User
|
| 139 |
-
|
| 140 |
-
if err := as.Db.Model(&models.User{}).Where("user_id = ?", session.UserID).Find(&result).Error; err != nil {
|
| 141 |
-
return nil, &types.AppError{Error: errors.New("failed to create or update user"), Code: http.StatusInternalServerError}
|
| 142 |
-
}
|
| 143 |
-
if len(result) == 0 {
|
| 144 |
-
if err := as.Db.Create(&user).Error; err != nil {
|
| 145 |
-
return nil, &types.AppError{Error: errors.New("failed to create or update user"), Code: http.StatusInternalServerError}
|
| 146 |
-
}
|
| 147 |
-
//Create root folder on first login
|
| 148 |
-
|
| 149 |
-
file := &models.File{
|
| 150 |
-
Name: "root",
|
| 151 |
-
Type: "folder",
|
| 152 |
-
MimeType: "drive/folder",
|
| 153 |
-
Path: "/",
|
| 154 |
-
Depth: utils.IntPointer(0),
|
| 155 |
-
UserID: session.UserID,
|
| 156 |
-
Status: "active",
|
| 157 |
-
ParentID: "root",
|
| 158 |
-
}
|
| 159 |
-
if err := as.Db.Create(file).Error; err != nil {
|
| 160 |
-
return nil, &types.AppError{Error: errors.New("failed to create or update user"), Code: http.StatusInternalServerError}
|
| 161 |
-
}
|
| 162 |
-
} else {
|
| 163 |
-
if err := as.Db.Model(&models.User{}).Where("user_id = ?", session.UserID).Update("tg_session", session.Sesssion).Error; err != nil {
|
| 164 |
-
return nil, &types.AppError{Error: errors.New("failed to create or update user"), Code: http.StatusInternalServerError}
|
| 165 |
-
}
|
| 166 |
-
}
|
| 167 |
-
setCookie(c, as.SessionCookieName, jweToken, as.SessionMaxAge)
|
| 168 |
-
return &schemas.Message{Status: true, Message: "login success"}, nil
|
| 169 |
-
}
|
| 170 |
-
|
| 171 |
-
func (as *AuthService) GetSession(c *gin.Context) *types.Session {
|
| 172 |
-
|
| 173 |
-
cookie, err := c.Request.Cookie(as.SessionCookieName)
|
| 174 |
-
|
| 175 |
-
if err != nil {
|
| 176 |
-
return nil
|
| 177 |
-
}
|
| 178 |
-
|
| 179 |
-
jwePayload, err := auth.Decode(cookie.Value)
|
| 180 |
-
|
| 181 |
-
if err != nil {
|
| 182 |
-
return nil
|
| 183 |
-
}
|
| 184 |
-
|
| 185 |
-
now := time.Now().UTC()
|
| 186 |
-
|
| 187 |
-
newExpires := now.Add(time.Duration(as.SessionMaxAge) * time.Second)
|
| 188 |
-
|
| 189 |
-
session := &types.Session{Name: jwePayload.Name, UserName: jwePayload.UserName, Expires: newExpires.Format(time.RFC3339)}
|
| 190 |
-
|
| 191 |
-
jwePayload.IssuedAt = jwt.NewNumericDate(now)
|
| 192 |
-
|
| 193 |
-
jwePayload.Expiry = jwt.NewNumericDate(newExpires)
|
| 194 |
-
|
| 195 |
-
jweToken, err := auth.Encode(jwePayload)
|
| 196 |
-
|
| 197 |
-
if err != nil {
|
| 198 |
-
return nil
|
| 199 |
-
}
|
| 200 |
-
setCookie(c, as.SessionCookieName, jweToken, as.SessionMaxAge)
|
| 201 |
-
return session
|
| 202 |
-
}
|
| 203 |
-
|
| 204 |
-
func (as *AuthService) Logout(c *gin.Context) (*schemas.Message, *types.AppError) {
|
| 205 |
-
val, _ := c.Get("jwtUser")
|
| 206 |
-
jwtUser := val.(*types.JWTClaims)
|
| 207 |
-
userId, _ := strconv.ParseInt(jwtUser.Subject, 10, 64)
|
| 208 |
-
|
| 209 |
-
client, _ := utils.GetAuthClient(c, jwtUser.TgSession, userId)
|
| 210 |
-
|
| 211 |
-
client.Run(c, func(ctx context.Context) error {
|
| 212 |
-
_, err := client.API().AuthLogOut(c)
|
| 213 |
-
return err
|
| 214 |
-
})
|
| 215 |
-
|
| 216 |
-
setCookie(c, as.SessionCookieName, "", -1)
|
| 217 |
-
return &schemas.Message{Status: true, Message: "logout success"}, nil
|
| 218 |
-
}
|
| 219 |
-
|
| 220 |
-
func prepareSession(user *tg.User, data *session.Data) *types.TgSession {
|
| 221 |
-
sessionString := generateTgSession(data.DC, data.AuthKey, 443)
|
| 222 |
-
session := &types.TgSession{
|
| 223 |
-
Sesssion: sessionString,
|
| 224 |
-
UserID: user.ID,
|
| 225 |
-
Bot: user.Bot,
|
| 226 |
-
UserName: user.Username,
|
| 227 |
-
Name: fmt.Sprintf("%s %s", user.FirstName, user.LastName),
|
| 228 |
-
IsPremium: user.Premium,
|
| 229 |
-
}
|
| 230 |
-
return session
|
| 231 |
-
}
|
| 232 |
-
|
| 233 |
-
func (as *AuthService) HandleMultipleLogin(c *gin.Context) {
|
| 234 |
-
upgrader := websocket.Upgrader{
|
| 235 |
-
CheckOrigin: func(r *http.Request) bool {
|
| 236 |
-
return true
|
| 237 |
-
},
|
| 238 |
-
}
|
| 239 |
-
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
| 240 |
-
if err != nil {
|
| 241 |
-
log.Println(err)
|
| 242 |
-
return
|
| 243 |
-
}
|
| 244 |
-
defer conn.Close()
|
| 245 |
-
|
| 246 |
-
dispatcher := tg.NewUpdateDispatcher()
|
| 247 |
-
loggedIn := qrlogin.OnLoginToken(dispatcher)
|
| 248 |
-
sessionStorage := &session.StorageMemory{}
|
| 249 |
-
tgClient, stop, _ := utils.StartNonAuthClient(dispatcher, sessionStorage)
|
| 250 |
-
|
| 251 |
-
defer stop()
|
| 252 |
-
|
| 253 |
-
for {
|
| 254 |
-
message := &SocketMessage{}
|
| 255 |
-
err := conn.ReadJSON(message)
|
| 256 |
-
|
| 257 |
-
if err != nil {
|
| 258 |
-
log.Println(err)
|
| 259 |
-
return
|
| 260 |
-
}
|
| 261 |
-
if message.AuthType == "qr" {
|
| 262 |
-
go func() {
|
| 263 |
-
authorization, err := tgClient.QR().Auth(c, loggedIn, func(ctx context.Context, token qrlogin.Token) error {
|
| 264 |
-
conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": map[string]string{"token": token.URL()}})
|
| 265 |
-
return nil
|
| 266 |
-
})
|
| 267 |
-
|
| 268 |
-
if tgerr.Is(err, "SESSION_PASSWORD_NEEDED") {
|
| 269 |
-
conn.WriteJSON(map[string]interface{}{"type": "auth", "message": "2FA required"})
|
| 270 |
-
return
|
| 271 |
-
}
|
| 272 |
-
|
| 273 |
-
if err != nil {
|
| 274 |
-
conn.WriteJSON(map[string]interface{}{"type": "error", "message": err.Error()})
|
| 275 |
-
return
|
| 276 |
-
}
|
| 277 |
-
user, ok := authorization.User.AsNotEmpty()
|
| 278 |
-
if !ok {
|
| 279 |
-
conn.WriteJSON(map[string]interface{}{"type": "error", "message": errors.New("auth failed")})
|
| 280 |
-
return
|
| 281 |
-
}
|
| 282 |
-
res, _ := sessionStorage.LoadSession(c)
|
| 283 |
-
sessionData := &SessionData{}
|
| 284 |
-
json.Unmarshal(res, sessionData)
|
| 285 |
-
session := prepareSession(user, &sessionData.Data)
|
| 286 |
-
conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": session, "message": "success"})
|
| 287 |
-
}()
|
| 288 |
-
}
|
| 289 |
-
if message.AuthType == "phone" && message.Message == "sendcode" {
|
| 290 |
-
go func() {
|
| 291 |
-
res, err := tgClient.Auth().SendCode(c, message.PhoneNo, tgauth.SendCodeOptions{})
|
| 292 |
-
if err != nil {
|
| 293 |
-
conn.WriteJSON(map[string]interface{}{"type": "error", "message": err.Error()})
|
| 294 |
-
return
|
| 295 |
-
}
|
| 296 |
-
code := res.(*tg.AuthSentCode)
|
| 297 |
-
conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": map[string]string{"phoneCodeHash": code.PhoneCodeHash}})
|
| 298 |
-
}()
|
| 299 |
-
}
|
| 300 |
-
if message.AuthType == "phone" && message.Message == "signin" {
|
| 301 |
-
go func() {
|
| 302 |
-
auth, err := tgClient.Auth().SignIn(c, message.PhoneNo, message.PhoneCode, message.PhoneCodeHash)
|
| 303 |
-
|
| 304 |
-
if errors.Is(err, tgauth.ErrPasswordAuthNeeded) {
|
| 305 |
-
conn.WriteJSON(map[string]interface{}{"type": "auth", "message": "2FA required"})
|
| 306 |
-
return
|
| 307 |
-
}
|
| 308 |
-
|
| 309 |
-
if err != nil {
|
| 310 |
-
conn.WriteJSON(map[string]interface{}{"type": "error", "message": err.Error()})
|
| 311 |
-
return
|
| 312 |
-
}
|
| 313 |
-
user, ok := auth.User.AsNotEmpty()
|
| 314 |
-
if !ok {
|
| 315 |
-
conn.WriteJSON(map[string]interface{}{"type": "error", "message": errors.New("auth failed")})
|
| 316 |
-
return
|
| 317 |
-
}
|
| 318 |
-
res, _ := sessionStorage.LoadSession(c)
|
| 319 |
-
sessionData := &SessionData{}
|
| 320 |
-
json.Unmarshal(res, sessionData)
|
| 321 |
-
session := prepareSession(user, &sessionData.Data)
|
| 322 |
-
conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": session, "message": "success"})
|
| 323 |
-
}()
|
| 324 |
-
}
|
| 325 |
-
|
| 326 |
-
if message.AuthType == "2fa" && message.Password != "" {
|
| 327 |
-
go func() {
|
| 328 |
-
auth, err := tgClient.Auth().Password(c, message.Password)
|
| 329 |
-
if err != nil {
|
| 330 |
-
conn.WriteJSON(map[string]interface{}{"type": "error", "message": err.Error()})
|
| 331 |
-
return
|
| 332 |
-
}
|
| 333 |
-
user, ok := auth.User.AsNotEmpty()
|
| 334 |
-
if !ok {
|
| 335 |
-
conn.WriteJSON(map[string]interface{}{"type": "error", "message": errors.New("auth failed")})
|
| 336 |
-
return
|
| 337 |
-
}
|
| 338 |
-
res, _ := sessionStorage.LoadSession(c)
|
| 339 |
-
sessionData := &SessionData{}
|
| 340 |
-
json.Unmarshal(res, sessionData)
|
| 341 |
-
session := prepareSession(user, &sessionData.Data)
|
| 342 |
-
conn.WriteJSON(map[string]interface{}{"type": "auth", "payload": session, "message": "success"})
|
| 343 |
-
}()
|
| 344 |
-
}
|
| 345 |
-
}
|
| 346 |
-
|
| 347 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
"fmt"
|
| 8 |
-
"io"
|
| 9 |
-
"math"
|
| 10 |
-
"net/http"
|
| 11 |
-
"strconv"
|
| 12 |
-
"strings"
|
| 13 |
-
|
| 14 |
-
"github.com/divyam234/teldrive/cache"
|
| 15 |
-
"github.com/divyam234/teldrive/models"
|
| 16 |
-
"github.com/divyam234/teldrive/schemas"
|
| 17 |
-
"github.com/divyam234/teldrive/utils"
|
| 18 |
-
|
| 19 |
-
"github.com/divyam234/teldrive/types"
|
| 20 |
-
|
| 21 |
-
"github.com/gin-gonic/gin"
|
| 22 |
-
"github.com/gotd/td/telegram"
|
| 23 |
-
"github.com/gotd/td/tg"
|
| 24 |
-
"github.com/jackc/pgx/v5/pgconn"
|
| 25 |
-
"github.com/mitchellh/mapstructure"
|
| 26 |
-
range_parser "github.com/quantumsheep/range-parser"
|
| 27 |
-
"gorm.io/gorm"
|
| 28 |
-
"gorm.io/gorm/clause"
|
| 29 |
-
)
|
| 30 |
-
|
| 31 |
-
type FileService struct {
|
| 32 |
-
Db *gorm.DB
|
| 33 |
-
ChannelID int64
|
| 34 |
-
}
|
| 35 |
-
|
| 36 |
-
func getAuthUserId(c *gin.Context) int64 {
|
| 37 |
-
val, _ := c.Get("jwtUser")
|
| 38 |
-
jwtUser := val.(*types.JWTClaims)
|
| 39 |
-
userId, _ := strconv.ParseInt(jwtUser.Subject, 10, 64)
|
| 40 |
-
return userId
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
func (fs *FileService) CreateFile(c *gin.Context) (*schemas.FileOut, *types.AppError) {
|
| 44 |
-
userId := getAuthUserId(c)
|
| 45 |
-
var fileIn schemas.FileIn
|
| 46 |
-
if err := c.ShouldBindJSON(&fileIn); err != nil {
|
| 47 |
-
return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest}
|
| 48 |
-
}
|
| 49 |
-
|
| 50 |
-
fileIn.Path = strings.TrimSpace(fileIn.Path)
|
| 51 |
-
|
| 52 |
-
if fileIn.Path != "" {
|
| 53 |
-
var parent models.File
|
| 54 |
-
if err := fs.Db.Where("type = ? AND path = ?", "folder", fileIn.Path).First(&parent).Error; err != nil {
|
| 55 |
-
return nil, &types.AppError{Error: errors.New("parent directory not found"), Code: http.StatusNotFound}
|
| 56 |
-
}
|
| 57 |
-
fileIn.ParentID = parent.ID
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
if fileIn.Type == "folder" {
|
| 61 |
-
fileIn.MimeType = "drive/folder"
|
| 62 |
-
var fullPath string
|
| 63 |
-
if fileIn.Path == "/" {
|
| 64 |
-
fullPath = "/" + fileIn.Name
|
| 65 |
-
} else {
|
| 66 |
-
fullPath = fileIn.Path + "/" + fileIn.Name
|
| 67 |
-
}
|
| 68 |
-
fileIn.Path = fullPath
|
| 69 |
-
fileIn.Depth = utils.IntPointer(len(strings.Split(fileIn.Path, "/")) - 1)
|
| 70 |
-
} else if fileIn.Type == "file" {
|
| 71 |
-
fileIn.Path = ""
|
| 72 |
-
fileIn.ChannelID = &fs.ChannelID
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
fileIn.UserID = userId
|
| 76 |
-
fileIn.Starred = utils.BoolPointer(false)
|
| 77 |
-
fileIn.Status = "active"
|
| 78 |
-
|
| 79 |
-
fileDb := mapFileInToFile(fileIn)
|
| 80 |
-
|
| 81 |
-
if err := fs.Db.Create(&fileDb).Error; err != nil {
|
| 82 |
-
pgErr := err.(*pgconn.PgError)
|
| 83 |
-
if pgErr.Code == "23505" {
|
| 84 |
-
return nil, &types.AppError{Error: errors.New("file exists"), Code: http.StatusBadRequest}
|
| 85 |
-
}
|
| 86 |
-
return nil, &types.AppError{Error: errors.New("failed to create a file"), Code: http.StatusBadRequest}
|
| 87 |
-
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
-
res := mapFileToFileOut(fileDb)
|
| 91 |
-
|
| 92 |
-
return &res, nil
|
| 93 |
-
}
|
| 94 |
-
|
| 95 |
-
func (fs *FileService) UpdateFile(c *gin.Context) (*schemas.FileOut, *types.AppError) {
|
| 96 |
-
|
| 97 |
-
fileID := c.Param("fileID")
|
| 98 |
-
|
| 99 |
-
var fileUpdate schemas.FileIn
|
| 100 |
-
|
| 101 |
-
var files []models.File
|
| 102 |
-
|
| 103 |
-
if err := c.ShouldBindJSON(&fileUpdate); err != nil {
|
| 104 |
-
return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest}
|
| 105 |
-
}
|
| 106 |
-
|
| 107 |
-
if fileUpdate.Type == "folder" && fileUpdate.Name != "" {
|
| 108 |
-
if err := fs.Db.Raw("select * from teldrive.update_folder(?, ?)", fileID, fileUpdate.Name).Scan(&files).Error; err != nil {
|
| 109 |
-
return nil, &types.AppError{Error: errors.New("failed to update the file"), Code: http.StatusInternalServerError}
|
| 110 |
-
}
|
| 111 |
-
} else {
|
| 112 |
-
fileDb := mapFileInToFile(fileUpdate)
|
| 113 |
-
if err := fs.Db.Model(&files).Clauses(clause.Returning{}).Where("id = ?", fileID).Updates(fileDb).Error; err != nil {
|
| 114 |
-
return nil, &types.AppError{Error: errors.New("failed to update the file"), Code: http.StatusInternalServerError}
|
| 115 |
-
}
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
-
if len(files) == 0 {
|
| 119 |
-
return nil, &types.AppError{Error: errors.New("file not updated"), Code: http.StatusNotFound}
|
| 120 |
-
}
|
| 121 |
-
|
| 122 |
-
file := mapFileToFileOut(files[0])
|
| 123 |
-
|
| 124 |
-
return &file, nil
|
| 125 |
-
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
func (fs *FileService) GetFileByID(c *gin.Context) (*schemas.FileOutFull, error) {
|
| 129 |
-
|
| 130 |
-
fileID := c.Param("fileID")
|
| 131 |
-
|
| 132 |
-
var file []models.File
|
| 133 |
-
|
| 134 |
-
fs.Db.Model(&models.File{}).Where("id = ?", fileID).Find(&file)
|
| 135 |
-
|
| 136 |
-
if len(file) == 0 {
|
| 137 |
-
return nil, errors.New("file not found")
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
return mapFileToFileOutFull(file[0]), nil
|
| 141 |
-
}
|
| 142 |
-
|
| 143 |
-
func (fs *FileService) ListFiles(c *gin.Context) (*schemas.FileResponse, *types.AppError) {
|
| 144 |
-
|
| 145 |
-
userId := getAuthUserId(c)
|
| 146 |
-
|
| 147 |
-
var pagingParams schemas.PaginationQuery
|
| 148 |
-
pagingParams.PerPage = 200
|
| 149 |
-
if err := c.ShouldBindQuery(&pagingParams); err != nil {
|
| 150 |
-
return nil, &types.AppError{Error: errors.New(""), Code: http.StatusBadRequest}
|
| 151 |
-
}
|
| 152 |
-
|
| 153 |
-
var sortingParams schemas.SortingQuery
|
| 154 |
-
sortingParams.Order = "asc"
|
| 155 |
-
sortingParams.Sort = "name"
|
| 156 |
-
if err := c.ShouldBindQuery(&sortingParams); err != nil {
|
| 157 |
-
return nil, &types.AppError{Error: errors.New(""), Code: http.StatusBadRequest}
|
| 158 |
-
}
|
| 159 |
-
|
| 160 |
-
var fileQuery schemas.FileQuery
|
| 161 |
-
fileQuery.Op = "list"
|
| 162 |
-
fileQuery.Status = "active"
|
| 163 |
-
fileQuery.UserID = userId
|
| 164 |
-
if err := c.ShouldBindQuery(&fileQuery); err != nil {
|
| 165 |
-
return nil, &types.AppError{Error: errors.New(""), Code: http.StatusBadRequest}
|
| 166 |
-
}
|
| 167 |
-
|
| 168 |
-
query := fs.Db.Model(&models.File{}).Limit(pagingParams.PerPage).
|
| 169 |
-
Where(map[string]interface{}{"user_id": userId, "status": "active"})
|
| 170 |
-
|
| 171 |
-
if fileQuery.Op == "list" {
|
| 172 |
-
|
| 173 |
-
if pathExists, message := fs.CheckIfPathExists(&fileQuery.Path); !pathExists {
|
| 174 |
-
return nil, &types.AppError{Error: errors.New(message), Code: http.StatusNotFound}
|
| 175 |
-
}
|
| 176 |
-
|
| 177 |
-
setOrderFilter(query, &pagingParams, &sortingParams)
|
| 178 |
-
|
| 179 |
-
query.Order("type DESC").Order(getOrder(sortingParams)).
|
| 180 |
-
Where("parent_id in (?)", fs.Db.Model(&models.File{}).Select("id").Where("path = ?", fileQuery.Path))
|
| 181 |
-
|
| 182 |
-
} else if fileQuery.Op == "find" {
|
| 183 |
-
|
| 184 |
-
filterQuery := map[string]interface{}{}
|
| 185 |
-
|
| 186 |
-
err := mapstructure.Decode(fileQuery, &filterQuery)
|
| 187 |
-
|
| 188 |
-
if err != nil {
|
| 189 |
-
return nil, &types.AppError{Error: err, Code: http.StatusBadRequest}
|
| 190 |
-
}
|
| 191 |
-
|
| 192 |
-
delete(filterQuery, "op")
|
| 193 |
-
|
| 194 |
-
if filterQuery["updated_at"] == nil {
|
| 195 |
-
delete(filterQuery, "updated_at")
|
| 196 |
-
}
|
| 197 |
-
|
| 198 |
-
setOrderFilter(query, &pagingParams, &sortingParams)
|
| 199 |
-
|
| 200 |
-
query.Order("type DESC").Order(getOrder(sortingParams)).Where(filterQuery)
|
| 201 |
-
|
| 202 |
-
} else if fileQuery.Op == "search" {
|
| 203 |
-
|
| 204 |
-
query.Where("teldrive.get_tsquery(?) @@ teldrive.get_tsvector(name)", fileQuery.Search)
|
| 205 |
-
|
| 206 |
-
setOrderFilter(query, &pagingParams, &sortingParams)
|
| 207 |
-
query.Order(getOrder(sortingParams))
|
| 208 |
-
|
| 209 |
-
}
|
| 210 |
-
|
| 211 |
-
var results []schemas.FileOut
|
| 212 |
-
|
| 213 |
-
query.Find(&results)
|
| 214 |
-
|
| 215 |
-
token := ""
|
| 216 |
-
|
| 217 |
-
if len(results) == pagingParams.PerPage {
|
| 218 |
-
lastItem := results[len(results)-1]
|
| 219 |
-
token = utils.GetField(&lastItem, utils.CamelToPascalCase(sortingParams.Sort))
|
| 220 |
-
token = base64.StdEncoding.EncodeToString([]byte(token))
|
| 221 |
-
}
|
| 222 |
-
|
| 223 |
-
res := &schemas.FileResponse{Results: results, NextPageToken: token}
|
| 224 |
-
|
| 225 |
-
return res, nil
|
| 226 |
-
}
|
| 227 |
-
|
| 228 |
-
func (fs *FileService) CheckIfPathExists(path *string) (bool, string) {
|
| 229 |
-
query := fs.Db.Model(&models.File{}).Select("id").Where("path = ?", path)
|
| 230 |
-
var results []schemas.FileOut
|
| 231 |
-
query.Find(&results)
|
| 232 |
-
if len(results) == 0 {
|
| 233 |
-
return false, "This directory doesn't exist."
|
| 234 |
-
}
|
| 235 |
-
return true, ""
|
| 236 |
-
}
|
| 237 |
-
|
| 238 |
-
func (fs *FileService) MakeDirectory(c *gin.Context) (*schemas.FileOut, *types.AppError) {
|
| 239 |
-
|
| 240 |
-
var payload schemas.MkDir
|
| 241 |
-
|
| 242 |
-
var files []models.File
|
| 243 |
-
|
| 244 |
-
if err := c.ShouldBindJSON(&payload); err != nil {
|
| 245 |
-
return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest}
|
| 246 |
-
}
|
| 247 |
-
|
| 248 |
-
userId := getAuthUserId(c)
|
| 249 |
-
if err := fs.Db.Raw("select * from teldrive.create_directories(?, ?)", userId, payload.Path).Scan(&files).Error; err != nil {
|
| 250 |
-
return nil, &types.AppError{Error: errors.New("failed to create directories"), Code: http.StatusInternalServerError}
|
| 251 |
-
}
|
| 252 |
-
|
| 253 |
-
file := mapFileToFileOut(files[0])
|
| 254 |
-
|
| 255 |
-
return &file, nil
|
| 256 |
-
|
| 257 |
-
}
|
| 258 |
-
|
| 259 |
-
func (fs *FileService) MoveFiles(c *gin.Context) (*schemas.Message, *types.AppError) {
|
| 260 |
-
|
| 261 |
-
var payload schemas.FileOperation
|
| 262 |
-
|
| 263 |
-
if err := c.ShouldBindJSON(&payload); err != nil {
|
| 264 |
-
return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest}
|
| 265 |
-
}
|
| 266 |
-
|
| 267 |
-
var destination models.File
|
| 268 |
-
|
| 269 |
-
if pathExists, message := fs.CheckIfPathExists(&payload.Destination); !pathExists {
|
| 270 |
-
return nil, &types.AppError{Error: errors.New(message), Code: http.StatusBadRequest}
|
| 271 |
-
}
|
| 272 |
-
|
| 273 |
-
if err := fs.Db.Model(&models.File{}).Select("id").Where("path = ?", payload.Destination).First(&destination).Error; errors.Is(err, gorm.ErrRecordNotFound) {
|
| 274 |
-
return nil, &types.AppError{Error: errors.New("destination not found"), Code: http.StatusNotFound}
|
| 275 |
-
|
| 276 |
-
}
|
| 277 |
-
|
| 278 |
-
if err := fs.Db.Model(&models.File{}).Where("id IN ?", payload.Files).UpdateColumn("parent_id", destination.ID).Error; err != nil {
|
| 279 |
-
return nil, &types.AppError{Error: errors.New("move failed"), Code: http.StatusInternalServerError}
|
| 280 |
-
}
|
| 281 |
-
|
| 282 |
-
return &schemas.Message{Status: true, Message: "files moved"}, nil
|
| 283 |
-
}
|
| 284 |
-
|
| 285 |
-
func (fs *FileService) DeleteFiles(c *gin.Context) (*schemas.Message, *types.AppError) {
|
| 286 |
-
|
| 287 |
-
var payload schemas.FileOperation
|
| 288 |
-
|
| 289 |
-
if err := c.ShouldBindJSON(&payload); err != nil {
|
| 290 |
-
return nil, &types.AppError{Error: errors.New("invalid request payload"), Code: http.StatusBadRequest}
|
| 291 |
-
}
|
| 292 |
-
|
| 293 |
-
if err := fs.Db.Exec("call teldrive.delete_files($1)", payload.Files).Error; err != nil {
|
| 294 |
-
return nil, &types.AppError{Error: errors.New("failed to delete files"), Code: http.StatusInternalServerError}
|
| 295 |
-
}
|
| 296 |
-
|
| 297 |
-
return &schemas.Message{Status: true, Message: "files deleted"}, nil
|
| 298 |
-
}
|
| 299 |
-
|
| 300 |
-
func (fs *FileService) GetFileStream(c *gin.Context) {
|
| 301 |
-
|
| 302 |
-
w := c.Writer
|
| 303 |
-
r := c.Request
|
| 304 |
-
|
| 305 |
-
fileID := c.Param("fileID")
|
| 306 |
-
|
| 307 |
-
var err error
|
| 308 |
-
|
| 309 |
-
res, err := cache.CachedFunction(fs.GetFileByID, fmt.Sprintf("files:%s", fileID))(c)
|
| 310 |
-
|
| 311 |
-
if err != nil {
|
| 312 |
-
http.Error(w, err.Error(), http.StatusBadRequest)
|
| 313 |
-
return
|
| 314 |
-
}
|
| 315 |
-
|
| 316 |
-
file := res.(*schemas.FileOutFull)
|
| 317 |
-
|
| 318 |
-
w.Header().Set("Accept-Ranges", "bytes")
|
| 319 |
-
|
| 320 |
-
var start, end int64
|
| 321 |
-
|
| 322 |
-
rangeHeader := r.Header.Get("Range")
|
| 323 |
-
|
| 324 |
-
if rangeHeader == "" {
|
| 325 |
-
start = 0
|
| 326 |
-
end = file.Size - 1
|
| 327 |
-
w.WriteHeader(http.StatusOK)
|
| 328 |
-
} else {
|
| 329 |
-
ranges, err := range_parser.Parse(file.Size, r.Header.Get("Range"))
|
| 330 |
-
if err != nil {
|
| 331 |
-
http.Error(w, err.Error(), http.StatusBadRequest)
|
| 332 |
-
return
|
| 333 |
-
}
|
| 334 |
-
start = ranges[0].Start
|
| 335 |
-
end = ranges[0].End
|
| 336 |
-
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, file.Size))
|
| 337 |
-
w.WriteHeader(http.StatusPartialContent)
|
| 338 |
-
}
|
| 339 |
-
|
| 340 |
-
contentLength := end - start + 1
|
| 341 |
-
|
| 342 |
-
w.Header().Set("Content-Type", file.MimeType)
|
| 343 |
-
|
| 344 |
-
w.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
|
| 345 |
-
|
| 346 |
-
disposition := "inline"
|
| 347 |
-
|
| 348 |
-
if c.Query("d") == "1" {
|
| 349 |
-
disposition = "attachment"
|
| 350 |
-
}
|
| 351 |
-
|
| 352 |
-
w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", disposition, file.Name))
|
| 353 |
-
|
| 354 |
-
client, idx := utils.GetDownloadClient(c)
|
| 355 |
-
|
| 356 |
-
defer func() {
|
| 357 |
-
utils.GetClientWorkload().Dec(idx)
|
| 358 |
-
}()
|
| 359 |
-
|
| 360 |
-
ir, iw := io.Pipe()
|
| 361 |
-
parts, err := fs.getParts(c, client, file)
|
| 362 |
-
if err != nil {
|
| 363 |
-
return
|
| 364 |
-
}
|
| 365 |
-
parts = rangedParts(parts, int64(start), int64(end))
|
| 366 |
-
|
| 367 |
-
if r.Method != "HEAD" {
|
| 368 |
-
go func() {
|
| 369 |
-
defer iw.Close()
|
| 370 |
-
for _, part := range parts {
|
| 371 |
-
streamFilePart(c, client, iw, &part, part.Start, part.End, 1024*1024)
|
| 372 |
-
}
|
| 373 |
-
}()
|
| 374 |
-
io.CopyN(w, ir, contentLength)
|
| 375 |
-
}
|
| 376 |
-
|
| 377 |
-
}
|
| 378 |
-
|
| 379 |
-
func (fs *FileService) getParts(ctx context.Context, tgClient *telegram.Client, file *schemas.FileOutFull) ([]types.Part, error) {
|
| 380 |
-
|
| 381 |
-
ids := []tg.InputMessageID{}
|
| 382 |
-
|
| 383 |
-
for _, part := range *file.Parts {
|
| 384 |
-
ids = append(ids, tg.InputMessageID{ID: int(part.ID)})
|
| 385 |
-
}
|
| 386 |
-
|
| 387 |
-
s := make([]tg.InputMessageClass, len(ids))
|
| 388 |
-
|
| 389 |
-
for i := range ids {
|
| 390 |
-
s[i] = &ids[i]
|
| 391 |
-
}
|
| 392 |
-
|
| 393 |
-
api := tgClient.API()
|
| 394 |
-
|
| 395 |
-
res, err := cache.CachedFunction(utils.GetChannelById, fmt.Sprintf("channels:%d", fs.ChannelID))(ctx, api, fs.ChannelID)
|
| 396 |
-
|
| 397 |
-
if err != nil {
|
| 398 |
-
return nil, err
|
| 399 |
-
}
|
| 400 |
-
|
| 401 |
-
channel := res.(*tg.Channel)
|
| 402 |
-
|
| 403 |
-
messageRequest := tg.ChannelsGetMessagesRequest{Channel: &tg.InputChannel{ChannelID: fs.ChannelID, AccessHash: channel.AccessHash},
|
| 404 |
-
ID: s}
|
| 405 |
-
|
| 406 |
-
res, err = cache.CachedFunction(api.ChannelsGetMessages, fmt.Sprintf("messages:%s", file.ID))(ctx, &messageRequest)
|
| 407 |
-
|
| 408 |
-
if err != nil {
|
| 409 |
-
return nil, err
|
| 410 |
-
}
|
| 411 |
-
|
| 412 |
-
messages := res.(*tg.MessagesChannelMessages)
|
| 413 |
-
|
| 414 |
-
parts := []types.Part{}
|
| 415 |
-
|
| 416 |
-
for _, message := range messages.Messages {
|
| 417 |
-
item := message.(*tg.Message)
|
| 418 |
-
media := item.Media.(*tg.MessageMediaDocument)
|
| 419 |
-
document := media.Document.(*tg.Document)
|
| 420 |
-
location := document.AsInputDocumentFileLocation()
|
| 421 |
-
parts = append(parts, types.Part{Location: location, Start: 0, End: document.Size - 1, Size: document.Size})
|
| 422 |
-
}
|
| 423 |
-
return parts, nil
|
| 424 |
-
}
|
| 425 |
-
|
| 426 |
-
func mapFileToFileOut(file models.File) schemas.FileOut {
|
| 427 |
-
return schemas.FileOut{
|
| 428 |
-
ID: file.ID,
|
| 429 |
-
Name: file.Name,
|
| 430 |
-
Type: file.Type,
|
| 431 |
-
MimeType: file.MimeType,
|
| 432 |
-
Path: file.Path,
|
| 433 |
-
Size: file.Size,
|
| 434 |
-
Starred: file.Starred,
|
| 435 |
-
ParentID: file.ParentID,
|
| 436 |
-
UpdatedAt: file.UpdatedAt,
|
| 437 |
-
}
|
| 438 |
-
}
|
| 439 |
-
|
| 440 |
-
func mapFileInToFile(file schemas.FileIn) models.File {
|
| 441 |
-
return models.File{
|
| 442 |
-
Name: file.Name,
|
| 443 |
-
Type: file.Type,
|
| 444 |
-
MimeType: file.MimeType,
|
| 445 |
-
Path: file.Path,
|
| 446 |
-
Size: file.Size,
|
| 447 |
-
Starred: file.Starred,
|
| 448 |
-
Depth: file.Depth,
|
| 449 |
-
UserID: file.UserID,
|
| 450 |
-
ParentID: file.ParentID,
|
| 451 |
-
Parts: file.Parts,
|
| 452 |
-
ChannelID: file.ChannelID,
|
| 453 |
-
Status: file.Status,
|
| 454 |
-
}
|
| 455 |
-
}
|
| 456 |
-
|
| 457 |
-
func mapFileToFileOutFull(file models.File) *schemas.FileOutFull {
|
| 458 |
-
return &schemas.FileOutFull{
|
| 459 |
-
FileOut: mapFileToFileOut(file),
|
| 460 |
-
Parts: file.Parts, ChannelID: file.ChannelID,
|
| 461 |
-
}
|
| 462 |
-
}
|
| 463 |
-
|
| 464 |
-
func setOrderFilter(query *gorm.DB, pagingParams *schemas.PaginationQuery, sortingParams *schemas.SortingQuery) *gorm.DB {
|
| 465 |
-
if pagingParams.NextPageToken != "" {
|
| 466 |
-
sortColumn := sortingParams.Sort
|
| 467 |
-
if sortColumn == "name" {
|
| 468 |
-
sortColumn = "name collate numeric"
|
| 469 |
-
} else {
|
| 470 |
-
sortColumn = utils.CamelToSnake(sortingParams.Sort)
|
| 471 |
-
}
|
| 472 |
-
|
| 473 |
-
tokenValue, err := base64.StdEncoding.DecodeString(pagingParams.NextPageToken)
|
| 474 |
-
if err == nil {
|
| 475 |
-
if sortingParams.Order == "asc" {
|
| 476 |
-
return query.Where(fmt.Sprintf("%s > ?", sortColumn), string(tokenValue))
|
| 477 |
-
} else {
|
| 478 |
-
return query.Where(fmt.Sprintf("%s < ?", sortColumn), string(tokenValue))
|
| 479 |
-
}
|
| 480 |
-
}
|
| 481 |
-
}
|
| 482 |
-
return query
|
| 483 |
-
}
|
| 484 |
-
|
| 485 |
-
func getOrder(sortingParams schemas.SortingQuery) string {
|
| 486 |
-
sortColumn := utils.CamelToSnake(sortingParams.Sort)
|
| 487 |
-
if sortingParams.Sort == "name" {
|
| 488 |
-
sortColumn = "name collate numeric"
|
| 489 |
-
}
|
| 490 |
-
|
| 491 |
-
return fmt.Sprintf("%s %s", sortColumn, strings.ToUpper(sortingParams.Order))
|
| 492 |
-
}
|
| 493 |
-
|
| 494 |
-
func chunk(ctx context.Context, tgClient *telegram.Client, part *types.Part, offset int64, limit int64) ([]byte, error) {
|
| 495 |
-
|
| 496 |
-
req := &tg.UploadGetFileRequest{
|
| 497 |
-
Offset: offset,
|
| 498 |
-
Limit: int(limit),
|
| 499 |
-
Location: part.Location,
|
| 500 |
-
}
|
| 501 |
-
|
| 502 |
-
r, err := tgClient.API().UploadGetFile(ctx, req)
|
| 503 |
-
|
| 504 |
-
if err != nil {
|
| 505 |
-
return nil, err
|
| 506 |
-
}
|
| 507 |
-
|
| 508 |
-
switch result := r.(type) {
|
| 509 |
-
case *tg.UploadFile:
|
| 510 |
-
return result.Bytes, nil
|
| 511 |
-
default:
|
| 512 |
-
return nil, fmt.Errorf("unexpected type %T", r)
|
| 513 |
-
}
|
| 514 |
-
}
|
| 515 |
-
|
| 516 |
-
func totalParts(start, end, chunkSize int64) int {
|
| 517 |
-
|
| 518 |
-
totalBytes := end - start + 1
|
| 519 |
-
parts := totalBytes / chunkSize
|
| 520 |
-
|
| 521 |
-
if totalBytes%chunkSize != 0 {
|
| 522 |
-
parts++
|
| 523 |
-
}
|
| 524 |
-
|
| 525 |
-
return int(parts)
|
| 526 |
-
}
|
| 527 |
-
|
| 528 |
-
func streamFilePart(ctx context.Context, tgClient *telegram.Client, writer *io.PipeWriter, part *types.Part, start, end, chunkSize int64) error {
|
| 529 |
-
|
| 530 |
-
offset := start - (start % chunkSize)
|
| 531 |
-
firstPartCut := start - offset
|
| 532 |
-
lastPartCut := (end % chunkSize) + 1
|
| 533 |
-
|
| 534 |
-
partCount := totalParts(start, end, chunkSize)
|
| 535 |
-
|
| 536 |
-
currentPart := 1
|
| 537 |
-
|
| 538 |
-
for {
|
| 539 |
-
r, _ := chunk(ctx, tgClient, part, offset, chunkSize)
|
| 540 |
-
|
| 541 |
-
if len(r) == 0 {
|
| 542 |
-
break
|
| 543 |
-
} else if partCount == 1 {
|
| 544 |
-
r = r[firstPartCut:lastPartCut]
|
| 545 |
-
|
| 546 |
-
} else if currentPart == 1 {
|
| 547 |
-
r = r[firstPartCut:]
|
| 548 |
-
|
| 549 |
-
} else if currentPart == partCount {
|
| 550 |
-
r = r[:lastPartCut]
|
| 551 |
-
|
| 552 |
-
}
|
| 553 |
-
|
| 554 |
-
writer.Write(r)
|
| 555 |
-
|
| 556 |
-
currentPart++
|
| 557 |
-
|
| 558 |
-
offset += chunkSize
|
| 559 |
-
|
| 560 |
-
if currentPart > partCount {
|
| 561 |
-
break
|
| 562 |
-
}
|
| 563 |
-
|
| 564 |
-
}
|
| 565 |
-
|
| 566 |
-
return nil
|
| 567 |
-
}
|
| 568 |
-
|
| 569 |
-
func rangedParts(parts []types.Part, start, end int64) []types.Part {
|
| 570 |
-
|
| 571 |
-
chunkSize := parts[0].Size
|
| 572 |
-
|
| 573 |
-
startPartNumber := utils.Max(int64(math.Ceil(float64(start)/float64(chunkSize)))-1, 0)
|
| 574 |
-
|
| 575 |
-
endPartNumber := int64(math.Ceil(float64(end) / float64(chunkSize)))
|
| 576 |
-
|
| 577 |
-
partsToDownload := parts[startPartNumber:endPartNumber]
|
| 578 |
-
partsToDownload[0].Start = start % chunkSize
|
| 579 |
-
partsToDownload[len(partsToDownload)-1].End = end % chunkSize
|
| 580 |
-
|
| 581 |
-
return partsToDownload
|
| 582 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 7 |
-
"net/http"
|
| 8 |
-
|
| 9 |
-
"github.com/divyam234/teldrive/cache"
|
| 10 |
-
"github.com/divyam234/teldrive/schemas"
|
| 11 |
-
"github.com/divyam234/teldrive/utils"
|
| 12 |
-
|
| 13 |
-
"github.com/divyam234/teldrive/types"
|
| 14 |
-
|
| 15 |
-
"github.com/divyam234/teldrive/models"
|
| 16 |
-
"github.com/gin-gonic/gin"
|
| 17 |
-
"github.com/gotd/td/telegram/message"
|
| 18 |
-
"github.com/gotd/td/telegram/uploader"
|
| 19 |
-
"github.com/gotd/td/tg"
|
| 20 |
-
"gorm.io/gorm"
|
| 21 |
-
)
|
| 22 |
-
|
| 23 |
-
type UploadService struct {
|
| 24 |
-
Db *gorm.DB
|
| 25 |
-
ChannelID int64
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
func (us *UploadService) GetUploadFileById(c *gin.Context) (*schemas.UploadOut, *types.AppError) {
|
| 29 |
-
uploadId := c.Param("id")
|
| 30 |
-
parts := []schemas.UploadPartOut{}
|
| 31 |
-
if err := us.Db.Model(&models.Upload{}).Order("part_no").Where("upload_id = ?", uploadId).Find(&parts).Error; err != nil {
|
| 32 |
-
return nil, &types.AppError{Error: errors.New("failed to fetch from db"), Code: http.StatusInternalServerError}
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
return &schemas.UploadOut{Parts: parts}, nil
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
func (us *UploadService) DeleteUploadFile(c *gin.Context) *types.AppError {
|
| 39 |
-
uploadId := c.Param("id")
|
| 40 |
-
if err := us.Db.Where("upload_id = ?", uploadId).Delete(&models.Upload{}).Error; err != nil {
|
| 41 |
-
return &types.AppError{Error: errors.New("failed to delete upload"), Code: http.StatusInternalServerError}
|
| 42 |
-
}
|
| 43 |
-
|
| 44 |
-
return nil
|
| 45 |
-
}
|
| 46 |
-
|
| 47 |
-
func (us *UploadService) UploadFile(c *gin.Context) (*schemas.UploadPartOut, *types.AppError) {
|
| 48 |
-
|
| 49 |
-
var uploadQuery schemas.UploadQuery
|
| 50 |
-
|
| 51 |
-
uploadQuery.PartNo = 1
|
| 52 |
-
uploadQuery.TotalParts = 1
|
| 53 |
-
|
| 54 |
-
if err := c.ShouldBindQuery(&uploadQuery); err != nil {
|
| 55 |
-
return nil, &types.AppError{Error: err, Code: http.StatusBadRequest}
|
| 56 |
-
}
|
| 57 |
-
|
| 58 |
-
if uploadQuery.Filename == "" {
|
| 59 |
-
return nil, &types.AppError{Error: errors.New("filename missing"), Code: http.StatusBadRequest}
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
uploadId := c.Param("id")
|
| 63 |
-
|
| 64 |
-
var uploadPart []models.Upload
|
| 65 |
-
|
| 66 |
-
us.Db.Model(&models.Upload{}).Where("upload_id = ?", uploadId).Where("part_no = ?", uploadQuery.PartNo).Find(&uploadPart)
|
| 67 |
-
|
| 68 |
-
if len(uploadPart) == 1 {
|
| 69 |
-
out := mapSchema(&uploadPart[0])
|
| 70 |
-
return out, nil
|
| 71 |
-
}
|
| 72 |
-
|
| 73 |
-
client, idx := utils.GetUploadClient(c)
|
| 74 |
-
|
| 75 |
-
file := c.Request.Body
|
| 76 |
-
|
| 77 |
-
fileSize := c.Request.ContentLength
|
| 78 |
-
|
| 79 |
-
fileName := uploadQuery.Filename
|
| 80 |
-
|
| 81 |
-
var msgId int
|
| 82 |
-
|
| 83 |
-
ctx := context.Background()
|
| 84 |
-
|
| 85 |
-
ctx, cancel := context.WithCancel(ctx)
|
| 86 |
-
|
| 87 |
-
defer func() {
|
| 88 |
-
if idx != -1 {
|
| 89 |
-
utils.GetClientWorkload().Dec(idx)
|
| 90 |
-
}
|
| 91 |
-
cancel()
|
| 92 |
-
}()
|
| 93 |
-
|
| 94 |
-
err := client.Run(ctx, func(ctx context.Context) error {
|
| 95 |
-
|
| 96 |
-
api := client.API()
|
| 97 |
-
|
| 98 |
-
u := uploader.NewUploader(api).WithThreads(8).WithPartSize(512 * 1024)
|
| 99 |
-
|
| 100 |
-
upload, err := u.Upload(c, uploader.NewUpload(fileName, file, fileSize))
|
| 101 |
-
|
| 102 |
-
if err != nil {
|
| 103 |
-
return err
|
| 104 |
-
}
|
| 105 |
-
|
| 106 |
-
document := message.UploadedDocument(upload).Filename(fileName).ForceFile(true)
|
| 107 |
-
|
| 108 |
-
res, err := cache.CachedFunction(utils.GetChannelById, fmt.Sprintf("channels:%d", us.ChannelID))(c, client.API(), us.ChannelID)
|
| 109 |
-
|
| 110 |
-
if err != nil {
|
| 111 |
-
return err
|
| 112 |
-
}
|
| 113 |
-
|
| 114 |
-
channel := res.(*tg.Channel)
|
| 115 |
-
|
| 116 |
-
sender := message.NewSender(client.API())
|
| 117 |
-
|
| 118 |
-
target := sender.To(&tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash})
|
| 119 |
-
|
| 120 |
-
res, err = target.Media(c, document)
|
| 121 |
-
|
| 122 |
-
if err != nil {
|
| 123 |
-
return err
|
| 124 |
-
}
|
| 125 |
-
|
| 126 |
-
updates := res.(*tg.Updates)
|
| 127 |
-
|
| 128 |
-
msgId = updates.Updates[0].(*tg.UpdateMessageID).ID
|
| 129 |
-
|
| 130 |
-
return nil
|
| 131 |
-
})
|
| 132 |
-
|
| 133 |
-
if err != nil {
|
| 134 |
-
return nil, &types.AppError{Error: err, Code: http.StatusInternalServerError}
|
| 135 |
-
}
|
| 136 |
-
|
| 137 |
-
partUpload := &models.Upload{
|
| 138 |
-
Name: fileName,
|
| 139 |
-
UploadId: uploadId,
|
| 140 |
-
PartId: msgId,
|
| 141 |
-
ChannelID: us.ChannelID,
|
| 142 |
-
Size: fileSize,
|
| 143 |
-
PartNo: uploadQuery.PartNo,
|
| 144 |
-
TotalParts: uploadQuery.TotalParts,
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
if err := us.Db.Create(partUpload).Error; err != nil {
|
| 148 |
-
return nil, &types.AppError{Error: errors.New("failed to upload part"), Code: http.StatusInternalServerError}
|
| 149 |
-
}
|
| 150 |
-
|
| 151 |
-
out := mapSchema(partUpload)
|
| 152 |
-
|
| 153 |
-
return out, nil
|
| 154 |
-
}
|
| 155 |
-
|
| 156 |
-
func mapSchema(in *models.Upload) *schemas.UploadPartOut {
|
| 157 |
-
out := &schemas.UploadPartOut{
|
| 158 |
-
ID: in.ID,
|
| 159 |
-
Name: in.Name,
|
| 160 |
-
PartId: in.PartId,
|
| 161 |
-
ChannelID: in.ChannelID,
|
| 162 |
-
PartNo: in.PartNo,
|
| 163 |
-
TotalParts: in.TotalParts,
|
| 164 |
-
Size: in.Size,
|
| 165 |
-
}
|
| 166 |
-
return out
|
| 167 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
services/user.service.go
DELETED
|
@@ -1,91 +0,0 @@
|
|
| 1 |
-
package services
|
| 2 |
-
|
| 3 |
-
import (
|
| 4 |
-
"bytes"
|
| 5 |
-
"context"
|
| 6 |
-
"fmt"
|
| 7 |
-
"net/http"
|
| 8 |
-
"strconv"
|
| 9 |
-
|
| 10 |
-
"github.com/divyam234/teldrive/types"
|
| 11 |
-
"github.com/divyam234/teldrive/utils"
|
| 12 |
-
"github.com/gotd/td/telegram"
|
| 13 |
-
"github.com/gotd/td/tg"
|
| 14 |
-
|
| 15 |
-
"github.com/gin-gonic/gin"
|
| 16 |
-
)
|
| 17 |
-
|
| 18 |
-
type UserService struct {
|
| 19 |
-
}
|
| 20 |
-
|
| 21 |
-
func getChunk(ctx context.Context, tgClient *telegram.Client, location tg.InputFileLocationClass, offset int64, limit int) ([]byte, error) {
|
| 22 |
-
|
| 23 |
-
req := &tg.UploadGetFileRequest{
|
| 24 |
-
Offset: offset,
|
| 25 |
-
Limit: int(limit),
|
| 26 |
-
Location: location,
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
r, err := tgClient.API().UploadGetFile(ctx, req)
|
| 30 |
-
|
| 31 |
-
if err != nil {
|
| 32 |
-
return nil, err
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
switch result := r.(type) {
|
| 36 |
-
case *tg.UploadFile:
|
| 37 |
-
return result.Bytes, nil
|
| 38 |
-
default:
|
| 39 |
-
return nil, fmt.Errorf("unexpected type %T", r)
|
| 40 |
-
}
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
func iterContent(ctx context.Context, tgClient *telegram.Client, location tg.InputFileLocationClass) (*bytes.Buffer, error) {
|
| 44 |
-
offset := int64(0)
|
| 45 |
-
limit := 1024 * 1024
|
| 46 |
-
buff := &bytes.Buffer{}
|
| 47 |
-
for {
|
| 48 |
-
r, err := getChunk(ctx, tgClient, location, offset, limit)
|
| 49 |
-
if err != nil {
|
| 50 |
-
return buff, err
|
| 51 |
-
}
|
| 52 |
-
if len(r) == 0 {
|
| 53 |
-
break
|
| 54 |
-
}
|
| 55 |
-
buff.Write(r)
|
| 56 |
-
offset += int64(limit)
|
| 57 |
-
}
|
| 58 |
-
return buff, nil
|
| 59 |
-
}
|
| 60 |
-
|
| 61 |
-
func (us *UserService) GetProfilePhoto(c *gin.Context) {
|
| 62 |
-
val, _ := c.Get("jwtUser")
|
| 63 |
-
jwtUser := val.(*types.JWTClaims)
|
| 64 |
-
userId, _ := strconv.ParseInt(jwtUser.Subject, 10, 64)
|
| 65 |
-
client, _ := utils.GetAuthClient(c, jwtUser.TgSession, userId)
|
| 66 |
-
|
| 67 |
-
err := client.Run(c, func(ctx context.Context) error {
|
| 68 |
-
self, err := client.Self(c)
|
| 69 |
-
if err != nil {
|
| 70 |
-
return err
|
| 71 |
-
}
|
| 72 |
-
peer := self.AsInputPeer()
|
| 73 |
-
photo, _ := self.Photo.AsNotEmpty()
|
| 74 |
-
location := &tg.InputPeerPhotoFileLocation{Big: false, Peer: peer, PhotoID: photo.PhotoID}
|
| 75 |
-
buff, err := iterContent(c, client, location)
|
| 76 |
-
if err != nil {
|
| 77 |
-
return err
|
| 78 |
-
}
|
| 79 |
-
content := buff.Bytes()
|
| 80 |
-
c.Writer.Header().Set("Content-Type", "image/jpeg")
|
| 81 |
-
c.Writer.Header().Set("Cache-Control", "public, max-age=86400")
|
| 82 |
-
c.Writer.Header().Set("Content-Length", strconv.Itoa(len(content)))
|
| 83 |
-
c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", "profile.jpeg"))
|
| 84 |
-
c.Writer.Write(content)
|
| 85 |
-
return nil
|
| 86 |
-
})
|
| 87 |
-
if err != nil {
|
| 88 |
-
http.Error(c.Writer, err.Error(), http.StatusBadRequest)
|
| 89 |
-
return
|
| 90 |
-
}
|
| 91 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|